Reputation: 528
In the following code, I was expecting something of length 96, but I get a list of length 48. Can you explain this result?
num_empty = 96
empty_vecs = as.list(1:num_empty)
for(i in 1:num_empty){empty_vecs[[i]] = c()}
length(empty_vecs)
[1] 48
Now I'll answer the question that led me to encounter this behavior. The original question was, "How do I make a list of empty vectors in R?" and the answer was "Replace c()
with character()
in the above code."
Upvotes: 6
Views: 661
Reputation: 44320
Setting list elements equal to c()
(aka NULL
) removes them, and this loop therefore has the effect of deleting every other element in your list. To see this, consider a smaller example, iteratively printing out the resulting vector:
e <- list(1, 2, 3, 4)
e
# [[1]]
# [1] 1
#
# [[2]]
# [1] 2
#
# [[3]]
# [1] 3
#
# [[4]]
# [1] 4
#
e[[1]] <- c()
e
# [[1]]
# [1] 2
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 4
#
e[[2]] <- c()
e
# [[1]]
# [1] 2
#
# [[2]]
# [1] 4
e[[3]] <- c()
e
# [[1]]
# [1] 2
#
# [[2]]
# [1] 4
e[[4]] <- c()
e
# [[1]]
# [1] 2
#
# [[2]]
# [1] 4
Note that if you actually wanted to create a list of 96 NULL values, you might try:
replicate(96, c(), FALSE)
Upvotes: 8