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."
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With