Reputation: 3764
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.
Upvotes: 3
Views: 726
Reputation: 206167
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.
Upvotes: 3