Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Adding an empty vector to a list

Tags:

list

r

In R, when I add an empty vector to a list, it is not in fact added, like below:

a = list()
a[[1]] = c()
print(length(a))

length(a) will be printed 0 in this case, while if I change the 2nd line to a[[1]] = c(1), then length of the list will be 1, as expected. In my implementation, I need the list length to be changed even if I add an empty vector to the list. Is there a way to do that?

like image 453
user5054 Avatar asked Aug 14 '17 01:08

user5054


1 Answers

Using things like vector() (logical) and character() assigns a specific class to an element you'd like to remain "empty". I would use the NULL class. You can assign a NULL list element by using [<- instead of [[<-.

a <- list()
a[1] <- list(NULL)
a
# [[1]]
# NULL
length(a)
# [1] 1
like image 148
Rich Scriven Avatar answered Sep 29 '22 08:09

Rich Scriven