How to make an empty vector of POSIXct

user3022875 picture user3022875 · Nov 21, 2014 · Viewed 8.7k times · Source

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-10-27 18:11:36 PDT"
vec

That does not work. Any ideas?

Answer

Rich Scriven picture Rich Scriven · Nov 21, 2014

Since there is no POSIX mode, you cannot initialize a POSIXct vector with vector() alone (see ?mode for a list of all mode types).

But we can use .POSIXct to create the vector from a character vector.

(x <- .POSIXct(character(10))) ## the same as .POSIXct(vector("character", 10))
# [1] NA NA NA NA NA NA NA NA NA NA
class(x)
# [1] "POSIXct" "POSIXt" 

Also note that you can also use .POSIXct(integer(10)) for a length 10 vector of origin date-times.