It is better to initialize the 'DF' as
DF_1 <- data.frame(days)
str(DF_1)
'data.frame': 2006 obs. of 1 variable:
$ days: Date, format: "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" ...
Or if we still want to use a for
loop, initialize with Date
class instead of logical
(matrix
creates the NA
row which are logical)
DF_1 <- data.frame(col1 = as.Date(rep(NA, length(days))))
Now, if we do the loop
for (i in 1:length(days)) {
print(days[i])
DF_1[i,1] <- days[i]
}
checking the class
str(DF_1)
'data.frame': 2006 obs. of 1 variable:
$ col1: Date, format: "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" ...
The issue is the coercion of Date
to its integer storage values. We can find the behavior also when unlist
unlist(as.list(head(days)))
[1] 16801 16802 16803 16804 16805 16806
or with unclass
unclass(head(days))
[1] 16801 16802 16803 16804 16805 16806
which can be corrected with c
in do.call
if the input is a list
do.call(c, as.list(head(days)))
[1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05" "2016-01-06"
or convert the integer back to Date
class afterwards by specifying the origin
in as.Date
as.Date(unlist(as.list(head(days))), origin = '1970-01-01')
[1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05" "2016-01-06"