Index of nested lists of named data frames using a character vector - R

I have a nested list of named data frames, for example:

mylist2 <- list(
  list(df1.a = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df2.b = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))),
  list(df3.c = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df4.d = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))),
  list(df5.e = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df6.f = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))))

I run a test (it doesn't matter which test), and it creates a character vector telling me which data frames in this list are important:

test
[1] "df1.a" "df5.e"

What is the most efficient way to extract these data frames from a nested list using this character vector? The test shows only the names of the second list, so it nestedlist[test]does not work.

+2
source share
2 answers

Since the OP mentioned that it is nested list, we can loop through the starting listone and then extract the elements of the second listusing[

lapply(mylist2, '[', test)

or using tidyverse

library(tidyverse)
map(mylist2, ~ .x %>% 
                   select(test))

Update

:

Filter(length, lapply(mylist2, function(x) x[intersect(test, names(x))]))
+1

, list s:

# Sample data
lst <- list(
    list(df1.a = 1, df2.b = 2),
    list(df3.c = 3, df4.d = 4),
    list(df5.e = 5, df6.f = 6))
test <- c("df1.a", "df5.e");

ret <- lapply(lst, function(x) x[names(x) %in% test])
ret[sapply(ret, length) > 0];
#[[1]]
#[[1]]$df1.a
#[1] 1
# 
# 
#[[2]]
#[[2]]$df5.e
#[1] 5
+1

Source: https://habr.com/ru/post/1696091/


All Articles