如何从R中的年份和儒略日(yday)获取日历日期

How to get calendar date from only year and julian day (yday) in R

我有一个数据集,其中有一列包含年份,一列包含每年的序号 (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

您可以从 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"


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