'Filtering using multiple variables and retaining those variables that meet criteria

I would like to filter using multiple variables in R. I got a way of doing so. How about if I only want to select the variables that meet the filtering criteria? Is there a way to this. In my example I would only to retain var1, var2 and var3.

library(tidyverse)

dat1 <- tibble(
  var1 = c("Math", "Kisw", "Computer", "Biology"),
  var2 = c("Science", "Geog", "Studies", "Math"),
  var3 = c("Kisw", "Math", "Phys", "Psychology"),
  var4 = rnorm(4, 80, 5)
)

# to filter

varfil <- dat1 %>% select(starts_with("var")) %>% names()

dat1 %>%
  filter(if_any(varfil, ~.x %in% c("Math", "Eng")))


Solution 1:[1]

filter is used to select rows, you should use select to select columns.

library(dplyr)

dat1 %>%
  select(where(~any(.x %in% c("Math", "Eng")))) %>%
  select(any_of(varfil))

#  var1     var2    var3      
#  <chr>    <chr>   <chr>     
#1 Math     Science Kisw      
#2 Kisw     Geog    Math      
#3 Computer Studies Phys      
#4 Biology  Math    Psychology 

Solution 2:[2]

In this case you should use select() + where():

dat1 %>%
  select(where(~ any(.x %in% c("Math", "Eng"))))

# # A tibble: 4 x 3
#   var1     var2    var3
#   <chr>    <chr>   <chr>
# 1 Math     Science Kisw
# 2 Kisw     Geog    Math
# 3 Computer Studies Phys
# 4 Biology  Math    Psychology

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronak Shah
Solution 2 Darren Tsai