R: Assigning POSIXct class to a data frame
When I assign a POSIXct object into a data frame, it converts it into the integer equivalent, for example:
> x<-as.data.frame(matri开发者_JAVA技巧x(nrow=1,ncol=2))
> x
V1 V2
1 NA NA
> x[1,1]<-as.POSIXct("2010-12-07 08:00:00")
> x
V1 V2
1 1291708800 NA
Is there a way to stop this behaviour, or to easily convert the integers back into POSIXct once I have done all the assignments?
You need to convert the column after you have already created it.
x <- as.data.frame(matrix(nrow=1,ncol=2))
class(x[1,1])
[1] "logical"
See how it was already assigned a class
. A matrix
can only have one data type.
x[,1] <- as.POSIXct(x[,1])
x[1,1] <- as.POSIXct("2010-12-07 08:00:00")
class(x[1,1])
[1] "POSIXt" "POSIXct"
x
V1 V2
1 2010-12-07 08:00:00 NA
Of course, it's unclear to me why you created it as an empty matrix to begin with. You can have just as easily have done:
x <- data.frame(date=as.POSIXct("2010-12-07 08:00:00"), value=NA)
I had exactly the same problem. To fix this, I declared the column class of the data frame using as.POSIXct()
.
Example:
> temp = data.frame(col1 = NA)
> temp[1,] = Sys.time()
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: num 1.4e+09
But
> temp = data.frame(col1 = as.POSIXct(NA,""))
> temp[1,] = Sys.time()
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: POSIXct, format: "2014-05-21 15:35:46"
Interestingly, even though the initial default column class is "logical"
:
> temp = data.frame(col1 = NA)
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: logi NA
You can write characters to it:
> temp = data.frame(col1 = NA)
> temp[1,] = "hello"
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: chr "hello"
However, like POSIXct
, you cannot write factors:
> temp = data.frame(col1 = NA)
> temp[1,] = as.factor("hello")
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: int 1
精彩评论