I have a very basic question regarding vectors in R. I want to create an empty vector and append dates to it. However, R converts the dates to “numeric”, i.e.
library(lubridate)
a <- c()
a <- c(a,now())
class(a)
results in
[1] "numeric"
Meanwhile, this code does exactly what I want:
a <- c(now())
a <- c(a,now())
class(a)
i.e. the class is correct now:
[1] “POSIXct” “POSIXt”
The problem is that I don’t want to initialize my vector with any date, i.e. I want it to be empty in the beginning.
I´ve tried to use list and then to “unlist” it (because I want to I want to pass these dates as an argument to functions like max() after) but it also gives me numerics:
a <- list()
a[[1]] <- now()
a[[2]] <- now()
class(unlist(a))
Using array doesn’t help me either.
Thus I’m a bit stuck. I’ve read the documentation regarding output type of vector in r but couldn’t find any solution. How can I create an empty vecto of dates, append a few dates and get the dates in the end? Thank you.
Remember that when you use
c()you don’t initialize a vector, but you create aNULLvalue. You need to usevector()to initiate a vector where you can manipulate the classes:Next to that, the solution of @juba is fine as long as there’s no timezone involved. If there is, you get the following :
In order to avoid this, you better copy the attributes, like this :
But in any case you shouldn’t be considering this at all, for the simple reason that appending a vector is a very slow process that can get you into trouble. If you have to save 100 dates in a vector, you better use either an lapply/sapply solution as Paul Hiemstra suggested, or you initiate your vector like :
or