简体   繁体   中英

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

I have a data set that has column containing year, and a column containing the ordinal (yday) day for each year. I would like to convert this information into a calendar date, so I can better filter the data set. The data looks like this, but is from 1980-2016 and has an entry for each day of the year:

year yday temp

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"))

I tried the following code, but could not get the correct calendar date: Convert day of year to date


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

You could start with January 1st, then calculate it by adding your yday values.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM