This is not a final decision, but I think it can help to understand.
Here is your details:
Data <- data.frame(date = as.Date(c('2000/01/01', '2012/01/02', '2013/01/03')))
Take these 2 vectors, one of which is specified by default as a number, and the second as Date.
vv <- vector("numeric",3) vv.Date <- vector("numeric",3) class(vv.Date) <- 'Date' vv [1] 0 0 0 > vv.Date [1] "1970-01-01" "1970-01-01" "1970-01-01"
Now, if I try to assign the first element of each vector, as you do in the first step of the loop:
vv[1] <- Data$date[1] vv.Date[1] <- Data$date[1] vv [1] 10957 0 0 > vv.Date [1] "2000-01-01" "1970-01-01" "1970-01-01"
As you can see, a typed vector is well created. What happens when you assign a vector to a scalar value, R tries to internally convert it to a vector type . To return to your example when you do this:
You create a numeric vector (vv) and you are trying to assign dates to it:
for(i in 1:3){ Data[i, "date3"] <- as.Date(Data[i, "date"]) }
If you type date 3, for example:
Data$date3 <- vv.Date
then you will try again
for(i in 1:3){ Data[i, "date3"] <- as.Date(Data[i, "date"]) }
You will get a good result:
date date3 1 2000-01-01 2000-01-01 2 2012-01-02 2012-01-02 3 2013-01-03 2013-01-03
agstudy
source share