Integer to POSIXlt

回眸只為那壹抹淺笑 提交于 2020-01-21 20:05:42

问题


I'm starting to get a handle on how base R handles dates/times, but still have some uncertainty.

Using the following data set (exert from meteorological data), I was able to convert to POSIXct and POSIXlt using the as.character() function. The Date.Time is provided in the format yymmddhhmm.

Date.Time <- c(1107151300, 1107151400, 1107151500, 1107151600, 1107151700, 1107151800)
WindSpd <-   c(11.8, 14.5, 14.9, 14.1, 15.2, 17.1)

##Using as.character()##
#Note POSIXlt this time
w <- data.frame(Date.Time, WindSpd)
w$Date.Time <- as.POSIXlt(as.character(w$Date.Time), format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
w

#Now POSIXct
x <- data.frame(Date.Time, WindSpd)
x$Date.Time <- as.POSIXct(as.character(x$Date.Time), format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
x

However, it seems silly to convert integers to characters in the sake of converting to a date. When I try to convert the integers directly, I get all NA values.

##Trying to coerce the intergers##
#note POSIXlt this time
y <- data.frame(Date.Time, WindSpd)
y$Date.Time <- as.POSIXlt(y$Date.Time, format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
y

#note POSIXct this time
z <- data.frame(Date.Time, WindSpd)
z$Date.Time <- as.POSIXct(z$Date.Time, format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
z

Obviously this isn't a crucial problem, as I've found a working solution. I would like to know anyways, as I'm trying to become a betteR codeR. What am I doing wrong in converting the integers to the R date classes? Also, are their benefits associated with POSIXlt vs POSIXct? According to the help article, it sounds like the only difference is how they are stored?


回答1:


There is an as.POSIXct.numeric method:

 > methods(as.POSIXct)
[1] as.POSIXct.date    as.POSIXct.Date    as.POSIXct.dates   as.POSIXct.default
[5] as.POSIXct.numeric as.POSIXct.POSIXlt

It uses numeric input as the number of seconds offset from the origin.

> as.POSIXct(1107151300, origin = '2011-07-15 13:00:00')
[1] "2046-08-14 19:01:40 PDT"
> as.POSIXct('1107151300', format = '%y%m%d%H%M', 
                          origin = '2011-07-15 13:00:00')
[1] "2011-07-15 13:00:00 PDT"

So, yes, you do need to use as.character.




回答2:


Try removing the format spec (I believe it is only needed for character input):

zz <- as.POSIXct(Date.Time, origin = '2011-07-15 13:00:00')

It will work if you supply Date.Time as time in actual seconds from '2011-07-15 13:00:00' with the correct time zone



来源:https://stackoverflow.com/questions/17413915/integer-to-posixlt

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