Access list element using get()

23,118

Solution 1

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" 

Solution 2

Why not simply:

example.list <- list(attribute="test")
listName <- "example.list"
get(listName)$attribute

# or, if both the list name and the element name are given as arguments:
elementName <- "attribute"
get(listName)[[elementName]]

Solution 3

If your strings contain more than just object names, e.g. operators like here, you can evaluate them as expressions as follows:

> string <- "example.list$attribute"
> eval(parse(text = string))
[1] "test"

If your strings are all of the type "object$attribute", you could also parse them into object/attribute, so you can still get the object, then extract the attribute with [[:

> parsed <- unlist(strsplit(string, "\\$"))
> get(parsed[1])[[parsed[2]]]
[1] "test"
Share:
23,118
mike
Author by

mike

Updated on April 30, 2021

Comments

  • mike
    mike about 3 years

    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.

  • Herman Toothrot
    Herman Toothrot over 7 years
    your first example is the one one that works for me, is it the most or only way to do it? I have a list of lists that I can only access by mylist[[1]][1] or mylist[[1]]$elementname.