How to initialize data.frame with column of type POSIXct?

风格不统一 提交于 2019-12-19 05:17:03

问题


I can initialize a data.frame via

df <- data.frame(a=numeric(), b=character())

But how do I define a column of type POSIXct?

df <- data.frame(a=numeric(), b=character(), c=POSIXct())

won't work.


回答1:


You can try

df <- data.frame(a=numeric(), b=character(), c=as.POSIXct(character()))

Similarly, you can create a POSIXct column of NAs in a data frame with > 0 rows by creating a new column with as.POSIXct(NA).




回答2:


An additional tip to the above initialization: If you begin rbind() activities to add rows to this empty data frame, you may encounter an error like the following if you follow this pattern:

oneDF <- rbind(oneDF,twoDF,stringsAsFactors=FALSE)
Error in as.POSIXct.default(value) :
  do not know how to convert 'value' to class "POSIXct"

I finally discovered that removing the stringsAsFactors=FALSE allowed for the POSIXct value (both integer time and time zone) to transfer to the target DF.

oneDF <- rbind(oneDF,twoDF)

examining the result:

unclass(oneDF$mytime)
[1] 1282089600
attr(,"tzone")
[1] "GMT"


来源:https://stackoverflow.com/questions/24250463/how-to-initialize-data-frame-with-column-of-type-posixct

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