DeduciveR
DeduciveR

Reputation: 1702

Using a list's assigned name from a character string in a vector

I have some lists:

my_list1 <- list("data" = list(c("a", "b", "c")), "meta" = list(c("a", "b")))
my_list2 <- list("data" = list(c("x", "y", "z")), "meta" = list(c("x", "y")))

I'd like to be able to perform some operations on these lists but I need to use the names of the lists stored in a vector as I'm creating them dynamically from an API call. Such a vector might be:

list_vec <- c("my_list1", "my_list2")

I'm running into problems evaluating the character string in the vector into the name of the list. I know this topic's been covered but the part I'm stuck on specifically is being able to extract just the data sublist when running functions within assign. Essentially a situation like this:

library(purrr)
for(i in seq_along(1:length(list_vec))){
  assign(list_vec[[i]], map_df(list_vec[[i]][["data"]], unlist))
}

Which would give a result of:

# A tibble: 3 x 1
  data 
  <chr>
1 a    
2 b    
3 c    

I could also do something like:

my_list1$meta <- NULL

with

list_vec[[1]][["meta"]] <- NULL

To reduce the list to just the data sublist, but I can't within dynamically assigned names.

I've also wrapping things with eval but can't get that to work.

So specifically I need to evaluate the list's name from a string so I can extract a sublist from it.

Upvotes: 1

Views: 789

Answers (1)

markus
markus

Reputation: 26373

We can pass the vector list_vec to mget, which returns a nested list. We use lapply to extract ([[) the data element and use unlist to convert this nested list to a list.

unlist(lapply(mget(list_vec), `[[`, "data"), recursive = FALSE)

Result

#$my_list1
#[1] "a" "b" "c"

#$my_list2
#[1] "x" "y" "z"

Upvotes: 1

Related Questions