4

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.

foehn
  • 431
  • 4
  • 13
  • Looks like a bug, or at least something strange in assignment functions. Note the difference between these: `L <- list(); L$a$b <- 1; is(L$a)` and `M <- list(); M[["a"]][["b"]] <- 1; is(M$a)`. – Ferdinand.kraft Aug 25 '13 at 17:29
  • Most surprising is that after setting `L[[a]][[b]] <- 1`, getting `L[[a]][[b]]` will give an error. – flodel Aug 25 '13 at 19:47
  • @flodel, do you use `a` or `"a"`? I get no error using strings. – Ferdinand.kraft Aug 25 '13 at 22:17

2 Answers2

5

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.

Dason
  • 60,663
  • 9
  • 131
  • 148
  • actually I'd like to store the results (vectors of characters of variable length) of my analysis. To do the analysis I have several steps, say step a and b, and for each step I have used different methods, say a1, a2... and b1, b2... Finally I want to store them in a nested list. Using such list structure benefits subsequent analysis, format, and save by loops, also makes my workspace more compact and neat. thanks. – foehn Aug 26 '13 at 04:23
  • If there is an answer that works best for you feel free to click the "checkmark" next to that answer to signify that that answer helped you most. – Dason Aug 26 '13 at 13:35
2

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.

Wojciech Sobala
  • 7,431
  • 2
  • 21
  • 27