Selecting colums based on row values

Viewed 46

I would like to subset columns (using a dplyr friendly method if possible) based on values in the rows.

The data frame looks like this but with more columns:

df <- 
data.frame(a = c("a","b","c","bingo"),
b = c("d","e","a","b"),
c = c("bingo","bingo","a","e"))

I want to select only columns that contains the value "bingo" something like

df %>% select(columns_that_contain("bingo"))

The expected output:

     a     c
1     a bingo
2     b bingo
3     c     a
4 bingo     e

Any help will be appreciated!

2 Answers

The select-helpers i.e. starts_with/ends_with/contains/matches are doing the match on the column names to select the columns. If we need to match values in a column, use where inside select and create a logical condition i.e. 'bingo' %in% . where . is the value of individual column and this returns a single TRUE/FALSE as the lhs of %in% is an element of length 1.

library(dplyr)
df %>% 
      select(where(~ 'bingo' %in% .))

Or another option is any

df %>%
    select(where(~ any(. == 'bingo')))

You can use the following code:

library(dplyr)
library(stringr)

df %>%
  select(where(~ any(str_detect(.x, "bingo"))))

      a     c
1     a bingo
2     b bingo
3     c     a
4 bingo     e

Related