How do I convert date to number of days, starting from the first day of the year.
How do I convert the following to the expected result below?
Dat
The %j
datetime formatting flag will give you the day of the year starting at 0.
d <- read.table(text='Date
02/01/2000
20/02/2000
12/12/2000
13/01/2001', header=TRUE)
d<-transform(d, NumDays=as.numeric(strftime(as.Date(Date, format='%d/%m/%Y'), '%j'))-1)
# Date NumDays
# 1 02/01/2000 1
# 2 20/02/2000 50
# 3 12/12/2000 346
# 4 13/01/2001 12
Then to add the TotalDays
, you can use cumsum
with some modular arithmetic,
transform(d, TotalDays=cumsum(c(1, ifelse(diff(NumDays) > 0, diff(NumDays), diff(NumDays) %% 365 + 1))))
# Date NumDays TotalDays
# 1 02/01/2000 1 1
# 2 20/02/2000 50 50
# 3 12/12/2000 346 346
# 4 13/01/2001 12 378
Or use this shorter alternative.
transform(d, TotalDays=cumsum(c(1, diff(as.Date(Date, format='%d/%m/%Y')))))