Preventing the conversion of a nested list R to a named vector

I want to create a nested list like

> L <- NULL > L$a$b <- 1 > L $a $a$b [1] 1 

Since I need to do assignment in loops, I have to use brackets instead of dollar, for example

 > L <- NULL > a <- "a" > b <- "b" > L[[a]][[b]] <- 1 > L a 1 > b <- "b1" > L[[a]][[b]] <- 1 Error in L[[a]][[b]] <- 1 : more elements supplied than there are to replace 

This is from my expectation: L becomes a named vector, not a nested list. However, if the assigned value is a vector whose length exceeds 1, the problem will disappear,

 > L <- NULL > L[[a]][[b]] <- 1:2 > L $a $a$b [1] 1 2 > b <- "b1" > L[[a]][[b]] <- 1 > L $a $a$b [1] 1 2 $a$b1 [1] 1 

Most of my assignments are longer than 1, which is the reason why my code seemed to work, but from time to time turned out to be strange. I want to know if there is a way to fix this unexpected behavior, thanks.

+4
source share
2 answers

You can clearly say that every thing should be its own list

 > L <- list() > L[[a]] <- list() > L[[a]][[b]] <- 1 > L $a $a$b [1] 1 

But there seems to be a better way to do what you want if you explain your actual purpose.

+5
source

see help ("[[")

When $ <- is applied to NULL x, it first forces x to list (). This also happens with [[<- if the value of the replacement value has a length greater than one: if the value has a length of 1 or 0, x is first forcibly bound to a vector of type zero length.

+2
source

Source: https://habr.com/ru/post/1498841/


All Articles