How to make an empty vector of POSIXct

后端 未结 6 1310
孤街浪徒
孤街浪徒 2021-02-12 03:21

I want to make an empty vector of POSIXct so that I can put a POSIXct in it:

vec <- vector(\"POSIXct\", 10)
vec
vec[1] <- \"2014-         


        
6条回答
  •  天涯浪人
    2021-02-12 04:06

    I would go for Gregor's solution. I first went with Rich Scriven's solution but then got an error when I tried to compute the difference for a Non-NA element later as shown in the example below

    t1 <- as.POSIXct("2014-10-27 18:11:36 PDT")
    t2 <- as.POSIXct("2014-11-20 18:11:36 PDT")
    x <- .POSIXct(character(10))
    x[1] <- t1
    
    difftime(t2, t1)
    #R Time difference of 24 days
    
    # fails
    difftime(t2, x[1])
    #R Error in unclass(time1) - unclass(time2) : 
    #R   non-numeric argument to binary operator
    
    unclass(x[1]) # character
    #R [1] "1414429896"
    unclass(t1)
    #R [1] 1414429896
    #R attr(,"tzone")
    #R [1] ""
    
    x <- .POSIXct(rep(NA_real_, 10))
    x[1] <- t1
    difftime(t2, x[1]) # all good
    #R Time difference of 24 days
    

    This can even lead to strange bugs like this one which can take a while to discover

    t1 <- as.POSIXct("2001-07-24 CEST")
    t2 <- as.POSIXct("2002-08-29 CEST")
    x <- .POSIXct(character(10))
    x[1] <- t1
    
    t2 < t1
    #R [1] FALSE
    t2 < x[1] # oh boy 
    #R [1] TRUE
    
    # the reason (I think)
    unclass(t2)
    #R [1] 1030572000
    #R attr(,"tzone")
    #R [1] ""
    unclass(x[1])
    #R [1] "995925600"
    
    "995925600" > 1030572000
    #R [1] TRUE
    

提交回复
热议问题