From help("[.data.frame")
:
For [ the replacement value can be a list: each element of the list is used to replace (part of) one column, recycling the list as necessary.
So you can do things like this:
df <- data.frame(a=1:2)
df[,2:3] <- list(3:4, 5:6)
# a V2 V3
#1 1 3 5
#2 2 4 6
However, this results in a warning:
df[,4] <- list(7, 8)
# Warning message:
# In `[<-.data.frame`(`*tmp*`, , 4, value = list(7, 8)) :
# provided 2 variables to replace 1 variables
# a V2 V3 V4
# 1 1 3 5 7
# 2 2 4 6 7
Now a POSIXlt
object is a list with 9 elements:
unclass(rep(as.POSIXlt(Sys.time()), 2))
# $sec
# [1] 1.958244 1.958244
#
# $min
# [1] 54 54
#
# $hour
# [1] 10 10
#
# $mday
# [1] 4 4
#
# $mon
# [1] 9 9
#
# $year
# [1] 113 113
#
# $wday
# [1] 5 5
#
# $yday
# [1] 276 276
#
# $isdst
# [1] 1 1
#
# attr(,"tzone")
# [1] "" "CET" "CEST"
Assigning this list to one column using [<-.data.frame
gives the warning you observed.
Potential solutions to the problem are simple:
- Use
POSIXct
and avoidPOSIXlt
. The only reason for using the latter is a need for extracting some of the list components, which is not often the case (and you can always coerce toPOSIXlt
, e.g., inside functions for rounding of time values). - Use
$<-.data.frame
. This is often cumbersome outside of interactive use. - Wrap the
POSIXlt
object in alist
for assignment:df[,1] <- list(POSIXlt_object)
.