How do I specify a range of columns in a case_when statemet to check a condition in R?

Viewed 207

Given the tibble -

library(tidyverse)
df <- mtcars %>% as_tibble() %>% slice(1:5)
df

# A tibble: 32 x 11
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1  21       6  160    110  3.9   2.62  16.5     0     1     4     4
 2  21       6  160    110  3.9   2.88  17.0     0     1     4     4
 3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
 4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1
 5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2

I know you can use something like df %>% select(c(mpg:vs)) to select a range of columns without typing all the column names in the select statement. How do I do something similar in a case_when statement. I have a dataset with about 35 columns and want to flag rows where all columns are equal to 0.

2 Answers

We can use where condition in select

df %>%
   select(where(~ all(. %in% c(0, 1))))

-output

# A tibble: 5 x 2
     vs    am
  <dbl> <dbl>
1     0     1
2     0     1
3     1     1
4     1     0
5     0     0

If we want to create a new column 'flag' that checks if all the column values are 0 for a particular row

df %>%
    mutate(new = !rowSums(cur_data() != 0))

I'm not sure if we can use case_when about this problem, but we can use the following solution:

library(dplyr)

df %>%
  rowwise() %>%
  mutate(flag = +(all(c_across(where(is.numeric)) == 0)))

# A tibble: 5 x 12
# Rowwise: 
    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb  flag
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
1  21       6   160   110  3.9   2.62  16.5     0     1     4     4     0
2  21       6   160   110  3.9   2.88  17.0     0     1     4     4     0
3  22.8     4   108    93  3.85  2.32  18.6     1     1     4     1     0
4  21.4     6   258   110  3.08  3.22  19.4     1     0     3     1     0
5  18.7     8   360   175  3.15  3.44  17.0     0     0     3     2     0
Related