dane = list(list(),list(),list())
for(n in 1:3){
for(m in 1:6){
dane[[n]][m] =c()
}
}
lengths(dane)
# [1] 5 5 5
Why does the result have sublists of length 5, not 6?
More minimally:
x = list()
for(i in 1:3) x[i] = NULL
length(x)
# [1] 2
## why is this 2, not 3?
CodePudding user response:
In the loop, the elements actually get deleted, not NULL
is stored in there. If you attempt to delete the n-th element of a list of zero length, a list with NULL
elements is created up to the penultimate element.
Try
x <- list()
length(x)
# [1] 0
x[5] <- NULL
x
# [[1]]
# NULL
#
# [[2]]
# NULL
#
# [[3]]
# NULL
#
# [[4]]
# NULL
where
length(x)
# [1] 4
To initialize a list with empty list elements recall that in R a list is also a vector.
li <- vector(mode='list', length=3L)
li
# [[1]]
# NULL
#
# [[2]]
# NULL
#
# [[3]]
# NULL