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.

4
  • 4
    Try myList[[name]]. Also, print requires parentheses in R, like print(x) not print x. Commented Mar 29, 2016 at 18:40
  • 1
    try myList[[name]] Commented Mar 29, 2016 at 18:40
  • Thank you so much! Commented Mar 29, 2016 at 18:41
  • paste(myList$, name, sep = "") is not valid R syntax. You need to quote all non-variable elements. Commented Mar 29, 2016 at 18:42

2 Answers 2

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]]

Sign up to request clarification or add additional context in comments.

2 Comments

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 Good to know that! Thank you sir!
1

I think you want something like this:

for (name in names(myList)) {
   print(myList[[name]]) 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.