How to use rlang to extract list value by name?

73 Views Asked by At

I am passing the name of a list element to a function as a string. I want to be able to extract the list element value by this name so I can use it dynamically with my function. Here is an MRE:

# function to reset list element at 
# 'tmp'. List files in folder which is 
# the list element value at 'tmp'.
x <- function(my_list, here){
  my_list %>% 
    purrr::list_modify(
      !!rlang::sym(here) := base::list.files(path = .$here)
  )
}

# folder with great files in it.
l <- base::list(tmp = 'folder/')

x(l, 'tmp')

I have tried rlang::sym with the here element, but to no avail. I believe I need .$, but maybe magrittr::aliases could be used instead. What is a solution?

Expected result:

# function to reset list element at 
# 'tmp'. List files in folder which is 
# the list element value at 'tmp'.
x <- function(my_list, here){
  my_list %>% 
    purrr::list_modify(
      !!rlang::sym(here) := base::list.files(path = .$tmp)
  )
}

# folder with great files in it.
l <- base::list(tmp = 'folder/')

x(l, 'tmp')
0

There are 0 best solutions below