Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select list element programmatically using name stored as string [duplicate]

Tags:

list

r

subset

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.

like image 899
NewbieDave Avatar asked Mar 29 '16 18:03

NewbieDave


2 Answers

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

like image 155
fhlgood Avatar answered Oct 19 '22 13:10

fhlgood


I think you want something like this:

for (name in names(myList)) {
   print(myList[[name]]) 
}
like image 32
darrelkj Avatar answered Oct 19 '22 11:10

darrelkj