How do I convert day-of-year to date? For example, what's the date for 104th day of 2004?
This is the opposite of How do you convert POSIX date to day of year in R?
How do I convert day-of-year to date? For example, what's the date for 104th day of 2004?
This is the opposite of How do you convert POSIX date to day of year in R?
I found that @TMS answer ignores the year specified in the origin, replacing it with the actual year you are executing the command (as @Shekeine found). Doing this seems to work fine though:
as.Date(104, origin = "2014-01-01")
CAUTION: day-of-year is zero based in this case!
origin="2013-12-31"
–
Poison This is the way I do it:
as.Date(104, format = "%j", origin = "1.1.2014")
# "2014-04-15"
PS: for those who wonder if answering my own question is encouraged, please look here: https://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-if-i-knew-the-answer-before-asking
[1] "2015-04-15"
for me. Running as.Date(1, format = "%j", origin=paste0("1.1.", "2015"))
returns "2015-01-02"
. What am I missing here? –
Escritoire For anyone working with many years of DOY data, here's an easy way to extract the date, month, and day from DOY using dplyr.
library(dplyr)
#
# create example dataframe
x <- data.frame(doy=c(rep(1:5, 3)),
year=c(rep(2010, 5), rep(2011, 5), rep(2012, 5)))
#
# change doy to dates using mutate()
x %>% mutate(date_= as.Date(doy-1, origin=paste0(year, "-01-01")),
month= strftime(date_, "%m"),
day=strftime(date_,"%d"))
# subtract 1 from doy because R uses a 0 base index
# otherwise DOY=1 will be Jan. 2.
# output:
doy year date_ month day
1 1 2010 2010-01-01 01 01
2 2 2010 2010-01-02 01 02
3 3 2010 2010-01-03 01 03
4 4 2010 2010-01-04 01 04
5 5 2010 2010-01-05 01 05
6 1 2011 2011-01-01 01 01
7 2 2011 2011-01-02 01 02
8 3 2011 2011-01-03 01 03
9 4 2011 2011-01-04 01 04
10 5 2011 2011-01-05 01 05
11 1 2012 2012-01-01 01 01
12 2 2012 2012-01-02 01 02
13 3 2012 2012-01-03 01 03
14 4 2012 2012-01-04 01 04
15 5 2012 2012-01-05 01 05
as.Date(2, origin = '2014-01-01')
As for the issue with above code giving the output as 2014-01-03.
You can just put the origin as the last day of the previous year.
as.Date(2, origin = '2013-12-31')
It works that way.
© 2022 - 2024 — McMap. All rights reserved.