R - convert POSIXct to fraction of julian day

假装没事ソ 提交于 2021-02-16 14:46:41

问题


How can a date/time object in R be transformed on the fraction of a julian day?

For example, how can I turn this date:

date <- as.POSIXct('2006-12-12 12:00:00',tz='GMT')

into a number like this

> fjday
[1] 365.5

where julian day is elapsed day counted from the january 1st. The fraction 0.5 means that it's 12pm, and therefore half of the day.

This is just an example, but my real data covers all the 365 days of year 2006.


回答1:


Since all your dates are from the same year (2006) this should be pretty easy:

julian(date, origin = as.POSIXct('2006-01-01', tz = 'GMT'))

If you or another reader happen to expand your dataset to other years, then you can set the origin for the beginning of each year as follows:

sapply(date, function(x) julian(x, origin = as.POSIXct(paste0(format(x, "%Y"),'-01-01'), tz = 'GMT')))



回答2:


Have a look at the difftime function:

> unclass(difftime('2006-12-12 12:00:00', '2006-01-01 00:00:00', tz="GMT", units = "days"))
[1] 345.5
attr(,"units")
[1] "days"



回答3:


A function to convert POSIX to julian day, an extension of the answer above, source it before using.

julian_conv <- function(x) { 
if (is.na(x)) { # Because julian() cannot accept NA values
  return(NA)
}
else {
j <-julian(x, origin = as.POSIXlt(paste0(format(x, "%Y"),'-01-01')))
temp <- unclass(j) # To unclass the object julian day to extract julian day
return(temp[1] + 1) # Because Julian day 1 is 1 e.g., 2016-01-01
}
}

Example:

date <- as.POSIXct('2006-12-12 12:00:00')
julian_conv(date)
#[1] 345.5


来源:https://stackoverflow.com/questions/27594235/r-convert-posixct-to-fraction-of-julian-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!