R: Assigning POSIXct class to a data frame

前端 未结 2 1727
别那么骄傲
别那么骄傲 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: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
    

提交回复
热议问题