Select list element programmatically using name stored as string

18,236

Solution 1

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

Solution 2

I think you want something like this:

for (name in names(myList)) {
   print(myList[[name]]) 
}
Share:
18,236
NewbieDave
Author by

NewbieDave

Updated on June 18, 2022

Comments

  • NewbieDave
    NewbieDave almost 2 years

    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.

  • Frank
    Frank about 8 years
    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).
  • fhlgood
    fhlgood about 8 years
    @Frank Good to know that! Thank you sir!