Search code examples
r

Extracting from list in R using the `$` function and variable names


Consider the following list:

example_list <- list(x = 1, y = 2, z = 3)

There are multiple ways to extract items from example_list; for example, example_list$x or example_list[["x"]] will work.

It is also possible to extract items from example_list by calling $ directly, i.e.,

`$`(example_list, "x")

However, the following does not work:

bork <- "x"
`$`(example_list, bork)       ## Returns NULL
`$`(example_list, eval(bork)) ## Returns error: invalid subscript type 'language'

How can I call $ directly with variable item names?

R version 4.4.0


Solution

  • You can use the [[ function to get items of a list using a variable.

    `[[`(example_list, bork) 
    

    This happens because of the way $ evaluates the second argument, acessing the expression in the argument instead of the content of the (string) object. [[ evaluated the object, so it is the proper method for accessing dynamically chosen items of a list.