R: Assigning POSIXct class to a data frame

前端 未结 2 1722
别那么骄傲
别那么骄傲 2021-01-06 20:36

When I assign a POSIXct object into a data frame, it converts it into the integer equivalent, for example:

> x<-as.data.frame(matrix(nrow=1,ncol=2))
&g         


        
相关标签:
2条回答
  • 2021-01-06 21:24

    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)
    
    0 讨论(0)
  • 2021-01-06 21:26

    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
    
    0 讨论(0)
提交回复
热议问题