user5054
user5054

Reputation: 1096

R: Adding an empty vector to a list

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?

Upvotes: 7

Views: 4613

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

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

Upvotes: 5

Related Questions