I have data for more than 3 years. For each year I want to find the day corresponding to Jaunary 1 of that year. For example:
> x <- c('5/5/2007','12/31/2007','1/2/2008')
> #Convert to day of year (julian date) –
> strptime(x,"%m/%d/%Y")$yday+1
[1] 125 365 2
I want to know how to do the same thing but with time added. But I still get the day not time. Can anyone suggest what is the better way to find the julian date with date and time ?
> x1 <- c('5/5/2007 02:00','12/31/2007 05:58','1/2/2008 16:25')
> #Convert to day of year (julian date) –
> strptime(x1,"%m/%d/%Y %H:%M")$yday+1
[1] 125 365 2
Rather than this result, I want the output in decimal days. For example the first example would be 125.0833333
and so on.
Thank you so much.
When dates are provided in the format of year followed by month followed by day, such as 2017-12-02, you can use the as.Date function.This tells R to think of them as being calendar dates. For example: months(as.Date("2017-12-02")) returns a value of December. weekdays(as.Date("2017-12-02")) returns a value of Saturday.
When dates are provided in the format of year followed by month followed by day, such as 2017-12-02, you can use the as.Date function.This tells R to think of them as being calendar dates. For example: as.Date ("2017-06-09") - as.Date ("2016-05-01") returns a value of of 404 and prints on the screen Time difference of 404 days.
Use rollback () if you want to change the date to the last day of the previous month or the first day of the month. To change the date to the first day of the month, use the roll_to_first argument and set it to TRUE. round up R release dates to hours round down R release dates to minutes
To convert year, month, and day of the month into a complete date, we can follow the below steps − Create a data frame with Year, Month and DayOfMonth as separate columns. Use mutate function of dplyr package to create complete date.
Are you hoping to get the day + a numerical part of a day as output? If so, something like this will work:
test <- strptime(x1,"%m/%d/%Y %H:%M")
(test$yday+1) + (test$hour/24) + (test$min/(24*60))
#[1] 125.083333 365.248611 2.684028
Although this matches what you ask for, I think removing the +1
might make more sense:
(test$yday) + (test$hour/24) + (test$min/(24*60))
#[1] 124.083333 364.248611 1.684028
Though my spidey senses are tingling that Dirk is going to show up and show me how to do this with a POSIXct
date/time representation.
Here is an attempt of such an answer using base functions:
mapply(julian, as.POSIXct(test), paste(format(test,"%Y"),"01","01",sep="-"))
#[1] 124.083333 364.248611 1.684028
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With