Home > OS >  How to access to an element of a list based on its name?
How to access to an element of a list based on its name?

Time:06-22

I'm trying to use the get() function to search for an object based on its name.
It usually works fine but when I want to use it to access an element of a list, it doesn't work anymore.
Here's my example :

mylist <- list(a = letters)
mylist$a
get("mylist$a") # => doesn't work !!!
get("mylist") # => works !

CodePudding user response:

You could do this several ways

mylist <- list(a = letters)

with(mylist, get("a"))
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
#> [19] "s" "t" "u" "v" "w" "x" "y" "z"

get("mylist")[["a"]]
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
#> [19] "s" "t" "u" "v" "w" "x" "y" "z"

get("mylist")$a
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
#> [19] "s" "t" "u" "v" "w" "x" "y" "z"

get("a", envir = list2env(mylist))
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
#> [19] "s" "t" "u" "v" "w" "x" "y" "z"

Created on 2022-06-22 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related