Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use startsWith. Uses base R:

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

or

subset(lst, startsWith(names(lst), "abc"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading