0

I have a list with 6 elements:

{
 "a": {
  "b": {
    "strA": {
      "strB": {
        "c": {
          "$": 8888
        }
      }
    }
  }
 }
}

print(unlist(a$b$strA$strB)) works if I type it in the values for strA and strB manually.

However, what I would like to do is itterate through the list in a loop with various values for strA and strB

for (i in 1:nrow(h)) {

  x=strsplit(x=h[i, 1], "\\.")   # this bit works for me
  y <- unlist(a)   # this bit works for me and gives me y[1] and y[2]

  if (x==a$b$y[1]$y[2]){   # this bit does not work yet
    <etc.>
  }
}  

The problem is that I cannot get the if clause to work on variables. How do I get this to work? Any help is greatly appreciated.

rvaneijk
  • 663
  • 6
  • 20
  • 2
    Why do you have these elements nested so deeply the list? – Señor O Aug 05 '15 at 15:39
  • 1
    It might help to `dput` your object, so we can make sure we're looking at the same thing. http://stackoverflow.com/a/28481250/1191259 – Frank Aug 05 '15 at 15:43

2 Answers2

1

It's not working because the object to the right of $ does not get evaluated, it is treated as a string (in other words, R is looking for an element called "y[1]" within a$b.

To access by dynamic variable, use a[["b"]][[y[1]]][[y[2]]]

But there's probably a better organization of data you can use than a deeply nested list.

Señor O
  • 17,049
  • 2
  • 45
  • 47
1

The alternative to mylist$myelement is mylist[['myelement']]. In the latter you can pass the string x <- 'myelement'. In other words mylist[[x]] will work where mylist$[x] would not.

Gabi
  • 1,303
  • 16
  • 20