Nick Knauer
Nick Knauer

Reputation: 4243

Subset rows that contain string in any column

I have a dataset like below:

  Col1      Col2     Col3
abckel        NA        7
jdmelw     njabc       NA
     8     jdken     jdne

How do I subset my dataset so that it only keeps rows that contain the string "abc"?

Final Expected Output:

  Col1      Col2     Col3
abckel        NA        7
jdmelw     njabc       NA

Upvotes: 0

Views: 2322

Answers (2)

Brigadeiro
Brigadeiro

Reputation: 2945

With your data.frame:

d <- data.frame("Col1" = c("abckel", "jdmelw", 8),
                "Col2" = c(NA, "njabc", NA),
                "Col3" = c(7, NA, "jdne"),
                stringsAsFactors = F)

The following should return your desired result:

d_new <- d[apply(d, 1, function(x) any(grepl("abc", x))), ]

Upvotes: 4

arg0naut91
arg0naut91

Reputation: 14764

A dplyr solution:

library(dplyr)

df %>% filter_all(any_vars(grepl("abc", .)))

Output:

     Col1  Col2 Col3
1: abckel  <NA>    7
2: jdmelw njabc <NA>

Upvotes: 3

Related Questions