Linked Questions

Popular Questions

If column with name contains partial value, keep rows

Asked by At

I have a dataset:

Camp1    Ade2    Camp3    Ade4    
   dA       1       eB       2
   dB       4       uC       8
   gB       3       NA      NA

How do I subset this dataset where if a column name that has "Camp" in the name does not contain values "A" or "B" or NA, exclude those rows.

I know how do it for exact matches but not partial.

cols = grepl("Camp", names(df))
rows = rowSums(df[, cols] == "A" | 
df[, cols] == "B" |
is.na(df[, cols])) == sum(cols)
df<-df[rows, ]

How do I do the equivalent but with partial matches?

Expected Output:

Camp1    Ade2    Camp3    Ade4    
   dA       1       eB       2
   gB       3       NA      NA

Related Questions