Search code examples
rlistvectornestednamed

preventing R nested list from being converted to named vector


I want to create a nested list, for example,

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

Since I need to do assignment in loops, I have to use the brackets instead of the 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

That is out of my expectation: L becomes a named vector rather than 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, that is the reason my code seemingly worked but at times failed strangely. I want to know if there is any way to fix this unexpected behavior, thanks.


Solution

  • You could explicitly say that each thing should be it's own list

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

    But it sounds like there is probably a better way to do what you want if you explain your actual goal.