简体   繁体   中英

Convert separate 'year' and 'day' columns into one 'date' column with lubridate?

I have one column for 'year' and one column for 'day' (julian day) and I want to use these columns to make a 'date' (2002-12-03 or any format is okay). I've found a lot of lubridate literature on breaking up dates, but am looking for how to put them together.

As simple as it sounds:

year    day    
2008    1
2008    2
2008    3
2008    4

to

year    day    date
2008    1    2008-1-1
etc.

You could use base dates rather than lubridate if you like

If this is your sample data

dd<-data.frame(
    year = rep(2008,4), 
    day = 1:4
)

Then you can run

years <- unique(dd$year)
yearstarts <- setNames(as.Date(paste0(years, "-01-01")), years)
newdates <- yearstarts[as.character(dd$year)] + dd$day - 1

Which produces

cbind(dd, newdates)

#   year day   newdates
# 1 2008   1 2008-01-01
# 2 2008   2 2008-01-02
# 3 2008   3 2008-01-03
# 4 2008   4 2008-01-04

This works because the base Date class stores the number of days since a particular sentinel value. So you when you add 1, you are adding one day to the current date. Here I assumed you may have multiple years to I make sure to correctly calculate the Date value for the first day of each year.

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