Home > Mobile >  Filtering using multiple variables and retaining those variables that meet criteria
Filtering using multiple variables and retaining those variables that meet criteria

Time:05-14

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")))

CodePudding user response:

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

CodePudding user response:

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 
  • Related