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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With