0

UPDATE: Combining the 2 suggestions in the comments, I got

dlist4[contains("M", names(dlist4))]
Error:
! `contains()` must be used within a *selecting* function.
ℹ See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.

or

dlist4 %>%select.list(., contains(names(.), "M"))
1: list(a = 1:4, b = 2:5)
2: list(a = 10:13, b = 5:8)
3: list(a = 10:13, b = 5:8)
4: list(a = 2:5, b = 5:8)

Selection: 

or

dlist4 %>% select(contains(names(.), "M"))
Error in `select()`:
! `select()` doesn't handle lists.
Run `rlang::last_error()` to see where the error occurred.

I'd like to extract all the nested lists with M_ in their names and save them to a new list without typing out the specific item.

dput(dlist4)
list(A = list(a = structure(1:4, dim = c(2L, 2L)), b = structure(2:5, dim = c(2L, 
2L))), G = list(a = structure(10:13, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))), M_1 = list(a = structure(10:13, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))), M_2 = list(a = structure(2:5, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))))

For this small list, I can do dlist4[c("M_1", "M_2")], but imagining a larger nested list with hundreds of lower level lists whose names either contain or start with "M_". Then, typing them all out would not be possible.

dlist4 %>% pluck("M_") gives NULL with no error so I don't know what's wrong with my code.

dlist4 %>% map(., ~{pluck("M_")}) returns an empty list and picks the wrong elements (A and G)

$A
[1] "M_"

$G
[1] "M_"

$M_1
[1] "M_"

$M_2
[1] "M_"
2
  • 2
    dlist4 %>% keep(startsWith(names(.), "M_")) May 26 at 6:44
  • 2
    dlist4[grep("^M_", names(dlist4))]
    – jay.sf
    May 26 at 6:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.