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

Subset a dataframe by row that contain a specific string anywhere inside the dataframe words

How could I subset a dataframe by a string that could be found anywhere in its columns? For example
"ol" exists only in the third row so that would give us only that row as result.

col1<-c("sd fgg","df dfg","fgh gdfg")
col2<-c("sd fgg","df dgfg","fgh gdfg")
col3<-c("sd fggg","dfg dfgg","fgghol gdfg")
df<-data.frame(col1,col2,col3)
 

>Solution :

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

Using R base

> df[unlist(sapply(df, function (x) grep("ol", x))),  ]
      col1     col2        col3
3 fgh gdfg fgh gdfg fgghol gdfg

A dplyr approach

df %>% 
  slice(.,
  rowwise(.) %>% 
  grep("ol", .) )
      col1     col2        col3
1 fgh gdfg fgh gdfg fgghol gdfg
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