Convert to day and time of year in R

I have data for more than 3 years. For every year I want to find a day corresponding to Yanaria 1 of that year. For instance:

> 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, but with added time. But I still get no time. Can anyone suggest the best way to find 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 

Instead of this result, I want to get the result in decimal days. For example, the first example would be 125.0833333 and so on.

Thank you very much.

+5
source share
3 answers

Do you expect to get the day + the numerical part of the day as an 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 is consistent with what you are asking, I think deleting +1 might make sense:

 (test$yday) + (test$hour/24) + (test$min/(24*60)) #[1] 124.083333 364.248611 1.684028 

Although my spidey feelings are tingling that Dirk is going to show and show me how to do this with the POSIXct date / time POSIXct .

Here is an attempt at such an answer using basic functions:

 mapply(julian, as.POSIXct(test), paste(format(test,"%Y"),"01","01",sep="-")) #[1] 124.083333 364.248611 1.684028 
+9
source

You can also use the POSIXct and POSIXlt with the firstof function from xts .

 x1 <- c("5/5/2007 02:00", "12/31/2007 05:58", "1/2/2008 16:25") x1 ## [1] "5/5/2007 02:00" "12/31/2007 05:58" "1/2/2008 16:25" y <- as.POSIXlt(x1, format = "%m/%d/%Y %H:%M") result <- mapply(julian, x = as.POSIXct(y), origin = firstof(y$year + 1900)) result ## [1] 124.083333 364.248611 1.684028 

if you do not want to use xts, maybe something like this

 result <- mapply(julian, x = as.POSIXct(x1, format = "%m/%d/%Y %H:%M", tz = "GMT"), origin = as.Date(paste0(gsub(".*([0-9]{4}).*", "\\1", x1), "-01-01"), tz = "GMT")) result ## [1] 124.083333 364.248611 1.684028 
+9
source

If you want to do the opposite (convert the day of the year to date and time), you can use this little function:

doy2date = function (mydoy) {
mydate = as.Date (mydoy, origin = "2008-01-01 00:00:00", tz = "GMT")
dech = (mydoy - as.integer (mydoy)) * 24
myh = as.integer (dech)
mym = as.integer ((dech - as.integer (dech)) * 60)
mys = round (I (((((dech - as.integer (dech)) * 60) - mym) * 60), digits = 0)
posixdate = as.POSIXct (paste (mydate, "", myh, ":", mym, ":", mys, sep = ""), tz = "GMT")
return (posixdate)
}

For example, if you try:

doy2date (117.6364)

The function will return "2008-04-27 15:16:25 GMT" as POSIXct.

0
source

All Articles