Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling list with empty vectors causes its length to change

Tags:

r

vector

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."

like image 292
eric_kernfeld Avatar asked Sep 09 '15 22:09

eric_kernfeld


People also ask

How do you create an empty vector of a certain length?

To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.

How do you make an empty list a certain length in R?

To create an empty list of specific length in R programming, call vector(mode, length) function and pass the value of “list” for mode, and an integer for length. The default values of the items in the list would be NULL.

Can you have an empty vector?

An empty vector can be created by simply not passing any value while creating a regular vector using the c() function. This will return NULL as an output.

How do you assign the length of a list in Python?

To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list. In this article, I will show you how to get the length of a list in 3 different ways.


1 Answers

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)
like image 134
josliber Avatar answered Sep 30 '22 21:09

josliber