How to make an empty vector of POSIXct

后端 未结 6 1296
孤街浪徒
孤街浪徒 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:09

    When creating a POSIXct vector in the following way, the underlying type becomes double:

    > times <- as.POSIXct(c("2015-09-18 09:01:05.984 CEST", "2015-09-18 10:01:10.984 CEST", "2015-09-18 10:21:20.584 CEST"))
    > typeof(times)
    [1] "double"
    > values <- c(5,6,7)
    

    Combining the above vector with an empty vector of POSIXct initialized with character as the underlying type, results in a character-POSIXct vector:

    > tm1 <- c(.POSIXct(character(0)), times)
    > typeof(tm1)
    [1] "character"
    

    ... which cannot be plotted directly:

    > ggplot() + geom_line(aes(x=tm1, y=val), data=data.frame(tm1,val))
    geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?
    

    I therefore prefer initializing my empty POSIXct vectors with double or integer as the underlying type:

    > tm2 <- c(.POSIXct(double(0)), times)
    > typeof(tm2)
    [1] "double"
    > ggplot() + geom_line(aes(x=tm2, y=val), data=data.frame(tm2,val))
    

    > tm3 <- c(.POSIXct(integer(0)), times)
    > typeof(tm3)
    [1] "double"
    > ggplot() + geom_line(aes(x=tm3, y=val), data=data.frame(tm3,val))
    #Same thing...
    

    When using double, the vector is also initialized with valid dates (which might or might not be preferable):

    > .POSIXct(character(10))
     [1] NA NA NA NA NA NA NA NA NA NA
    > .POSIXct(double(10))
     [1] "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET"
     [7] "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET" "1970-01-01 01:00:00 CET"
    

提交回复
热议问题