Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
foehn Avatar asked Mar 23 '23 15:03

foehn


2 Answers

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.

like image 131
Dason Avatar answered Mar 25 '23 05:03

Dason


see help("[[")

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

like image 24
Wojciech Sobala Avatar answered Mar 25 '23 03:03

Wojciech Sobala