16

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.

JerryWho
  • 3,060
  • 6
  • 27
  • 49
  • 5
    Maybe `df <- data.frame(a=numeric(), b=character(), c=as.POSIXct(character()))` does what you want? – konvas Jun 17 '14 at 16:01
  • @konvas Thanks, that was, what I was looking for. You can write it as answer and I'll give you the reward. – JerryWho Jun 21 '14 at 16:16

2 Answers2

17

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).

joran
  • 169,992
  • 32
  • 429
  • 468
konvas
  • 14,126
  • 2
  • 40
  • 46
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:

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"
Robert Casey
  • 1,511
  • 18
  • 19