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.
$
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]]
I think you want something like this:
for (name in names(myList)) {
print(myList[[name]])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With