A filled list with an empty vector causes its length to change

In the following code, I expect something of length 96, but I get a list of length 48 Can you explain the 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 will answer the questions that led me to this behavior The initial question was, "how do I list empty bodies in R?" The answer is "replace c () with the character () in the code above."

Solution

Setting list elements equal to C () (also known as null) deletes them, so the loop has the effect of deleting every other element in the list To see this, consider a smaller example of iteratively printing out the result 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 really want to create a list of 96 null values, you can try:

replicate(96,c(),FALSE)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>