【问题标题】:How to get calendar date from only year and julian day (yday) in R如何在R中仅从年份和儒略日(yday)获取日历日期
【发布时间】:2018-04-29 08:40:52
【问题描述】:

我有一个数据集,其中有一列包含年份,一列包含每年的序数(yday)日。我想将此信息转换为日历日期,以便更好地过滤数据集。数据看起来像这样,但是是从 1980 年到 2016 年,并且一年中的每一天都有一个条目:

年日气温

1980 1 0.5
1980 2 -5.0
1980 3 -3.5
1980 4 1.0
1980 5 -1.0

temps<-structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L), yday = 1:5, 
    temp = c(0.5, -5, -3.5, 1, -1)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("year", "yday", "temp"))

我尝试了以下代码,但无法获得正确的日历日期: Convert day of year to date

【问题讨论】:

    标签: r date tidyverse lubridate


    【解决方案1】:


    library(lubridate)
    library(dplyr)
    
    temps <- tibble::tribble(
      ~year, ~yday, ~temp,
      1980L,    1L,    0.5,
      1980L,    2L,     -5,
      1980L,    3L,   -3.5,
      1980L,    4L,      1,
      1980L,    5L,     -1,
      1980L,    99L,    -1,
      1980L,    50L,    -1
    )
    
    temps %>% 
      mutate(date = make_date(year) + yday - 1)
    
    #> # A tibble: 7 x 4
    #>    year  yday  temp       date
    #>   <int> <int> <dbl>     <date>
    #> 1  1980     1   0.5 1980-01-01
    #> 2  1980     2  -5.0 1980-01-02
    #> 3  1980     3  -3.5 1980-01-03
    #> 4  1980     4   1.0 1980-01-04
    #> 5  1980     5  -1.0 1980-01-05
    #> 6  1980    99  -1.0 1980-04-08
    #> 7  1980    50  -1.0 1980-02-19
    

    【讨论】:

      【解决方案2】:

      您可以从 1 月 1 日开始,然后通过添加您的 yday 值来计算它。

      with(temps, as.Date(paste0(year, "-01-01")) + (yday - 1))
      # [1] "1980-01-01" "1980-01-02" "1980-01-03" "1980-01-04" "1980-01-05"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-25
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多