Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access list element using get()

Tags:

string

loops

list

r

I'm trying to use get() to access a list element in R, but am getting an error.

example.list <- list()
example.list$attribute <- c("test")
get("example.list") # Works just fine
get("example.list$attribute") # breaks

## Error in get("example.list$attribute") : 
##  object 'example.list$attribute' not found

Any tips? I am looping over a vector of strings which identify the list names, and this would be really useful.

like image 976
mike Avatar asked Feb 26 '12 00:02

mike


People also ask

How do you access elements in a list?

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string. We use the index operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index. Remember that the indices start at 0.

How do you access a list in Python?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official python.org list docs.)

How do I get the list element in R?

Accessing List Elements. Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.


1 Answers

Here's the incantation that you are probably looking for:

get("attribute", example.list)
# [1] "test"

Or perhaps, for your situation, this:

get("attribute", eval(as.symbol("example.list")))
# [1] "test"

# Applied to your situation, as I understand it...

example.list2 <- example.list 
listNames <- c("example.list", "example.list2")
sapply(listNames, function(X) get("attribute", eval(as.symbol(X))))
# example.list example.list2 
#       "test"        "test" 
like image 103
Josh O'Brien Avatar answered Sep 21 '22 12:09

Josh O'Brien