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 a NULL
value. You need to use vector()
to initiate a vector where you can manipulate the classes:
> identical(c(),NULL)
[1] TRUE
> identical(c(),vector())
[1] FALSE
Next to that, the solution of @juba is fine as long as there's no timezone involved. If there is, you get the following :
> a <- vector()
> class(a) <- 'POSIXct'
> b <- as.POSIXct(as.character(Sys.time()),tz="GMT")
> b
[1] "2013-01-29 14:10:32 GMT"
> c(a,b)
[1] "2013-01-29 15:10:32 CET"
In order to avoid this, you better copy the attributes, like this :
> attributes(X) <- attributes(b)
> a <- vector()
> b <- as.POSIXct(as.character(Sys.time()),tz="GMT")
> X <- c(a,b)
> attributes(X) <- attributes(b)
> X
[1] "2013-01-29 14:10:32 GMT"
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 :
> a <- vector("numeric",100)
> class(a) <- c('POSIXct','POSIXt')
or
> a <- vector("numeric",100)
> attributes(a) <- list(class=c("POSIXct","POSIXt"),tzone="CET")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With