如何使用POSIXct类型的列初始化data.frame?

时间:2022-04-18 16:33:09

I can initialize a data.frame via

我可以通过初始化data.frame

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

But how do I define a column of type POSIXct?

但是如何定义POSIXct类型的列?

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

won't work.

2 个解决方案

#1


11  

You can try

你可以试试

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

#2


1  

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:

上述初始化的另一个提示:如果您开始向这个空数据框添加行的rbind()活动,如果您遵循以下模式,则可能会遇到如下错误:

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.

我终于发现删除stringsAsFactors = FALSE允许POSIXct值(整数时间和时区)转移到目标DF。

oneDF <- rbind(oneDF,twoDF)

examining the result:

检查结果:

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

#1


11  

You can try

你可以试试

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

#2


1  

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:

上述初始化的另一个提示:如果您开始向这个空数据框添加行的rbind()活动,如果您遵循以下模式,则可能会遇到如下错误:

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.

我终于发现删除stringsAsFactors = FALSE允许POSIXct值(整数时间和时区)转移到目标DF。

oneDF <- rbind(oneDF,twoDF)

examining the result:

检查结果:

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