Search code examples
rstringliststringr

Pull items from a named list based on string pattern R


I'm trying to pull similarly named items out of a list based on a shared string pattern for instance

> df1<- data.frame(1:5)
> df2 <-data.frame(11:15)
> df3 <-data.frame(26:30)
> df4 <- data.frame (36:40)
> 
> lst<- list(
+   abc.1 = df1, 
+   abc.2 =df2, 
+   cat = df3, 
+   husky =df4)
> 
> print(lst)
$abc.1
  X1.5
1    1
2    2
3    3
4    4
5    5

$abc.2
  X11.15
1     11
2     12
3     13
4     14
5     15

$cat
  X26.30
1     26
2     27
3     28
4     29
5     30

$husky
  X36.40
1     36
2     37
3     38
4     39
5     40

I'd like to use something similar to stringr::str_detect to pull the two list with 'abc' in the name, and omit the others.

Edited for formatting


Solution

  • Use startsWith. Uses base R:

    lst[startsWith(names(lst), "abc")]
    

    or

    subset(lst, startsWith(names(lst), "abc"))
    

    We can also combine it with keep_at in purrr:

    lst %>% keep_at(~ startsWith(.x, "abc"))