Reputation: 4416
I would like to figure out a way to convert a day into a decimal where 0 is January 1 and December 31 is 1. No time here just days. I looked for a few solutions like here and here but neither of those solution seem to fit my problem. I also had hopes for the date_decimal
function in lubridate
. I have figured out a solution which involves converting the Date
into a number, merging a dataframe that accounts for leaps years then divides the number by the total number of days in the year.
library(lubridate)
library(dplyr)
df <- data.frame(Date=seq(as.Date("2003/2/10"), as.Date("2007/2/10"), "years"),
var=seq(1,5, by=1))
lubridate
function attempt:
date_decimal(df$Date)
Leap year dataframe
maxdaydf<-data.frame(Year=seq(2003,2007,by=1), maxdays=c(365,366,365,365,365))
A dplyr
pipe to generate the daydecimal
:
df %>%
mutate(Year=year(Date), daynum=yday(Date)) %>%
full_join(maxdaydf, by=c("Year")) %>%
mutate(daydecimal=daynum/maxdays)
But as I said this is clunky and involves a 2nd dataframe which is never ideal. Any suggestions on how I can convert some Dates into decimals?
Upvotes: 0
Views: 131
Reputation: 19544
Instead of date_decimal()
you could use decimal_date()
decimal_date(df$Date)
[1] 2003.110 2004.109 2005.110 2006.110 2007.110
Or you can use :
yday(df$Date)/yday(ISOdate(year(df$Date), 12,31))
[1] 0.1123288 0.1120219 0.1123288 0.1123288 0.1123288
Upvotes: 2