8

I have a list

myList = list(a = 1, b = 2)
names(myList)
# [1] "a" "b" 

I want to select element from 'myList' by name stored in as string.

for (name in names(myList)){
     print (myList$name)
}

This is not working because name = "a", "b". My selecting line actually saying myList$"a" and myList$"b". I also tried:

print(myList$get(name))
print(get(paste(myList$, name, sep = "")))

but didn't work. Thank you very much if you could tell me how to do it.

Henrik
  • 65,555
  • 14
  • 143
  • 159
NewbieDave
  • 1,199
  • 3
  • 12
  • 23

2 Answers2

9

$ does exact and partial match, myList$name is equivalent to

`$`(myList, name)

As @Frank pointed out, the second argument name won't be evaluated, but be treated as a literal character string. Try ?`$`and see the document.

In your example. myList$name will try to look for name element in myList

That is why you need myList[[name]]

fhlgood
  • 479
  • 4
  • 9
  • 2
    I think "for exact match" might not be a full explanation. In fact, `$` supports *partial matching*. The point is that `$` does not evaluate it's second argument (the part that appears on the right hand side). Btw, to escape the backquote, you can use a backslash or nest the code excerpt in some extra `\``s (though I'm not sure how many are needed). – Frank Mar 29 '16 at 18:43
  • 1
    @Frank Good to know that! Thank you sir! – fhlgood Mar 29 '16 at 18:48
1

I think you want something like this:

for (name in names(myList)) {
   print(myList[[name]]) 
}
darrelkj
  • 142
  • 2