Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing list with NULL has unexpected length

Tags:

list

for-loop

r

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?
like image 474
Lukas015 Avatar asked Sep 08 '25 16:09

Lukas015


1 Answers

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
like image 163
jay.sf Avatar answered Sep 10 '25 07:09

jay.sf