Home > Software design >  Using multiple conditions in selecting variables in using where clause
Using multiple conditions in selecting variables in using where clause

Time:09-09

For this case I would like select variables with any instance of Math and Eng and the numeric variables.

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),
  var5 = c("Yes", "No", "Yes", "No"),
  var6 = c("No", "Yes", "No", "No"),
  var7 = rnorm(4, 80, 5),
  var8 = rnorm(4, 80, 5),
)

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

CodePudding user response:

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

Output:

# A tibble: 4 x 6
   var4  var7  var8 var1     var2    var3      
  <dbl> <dbl> <dbl> <chr>    <chr>   <chr>     
1  85.5  82.0  72.8 Math     Science Kisw      
2  83.9  80.8  88.3 Kisw     Geog    Math      
3  75.5  86.1  88.7 Computer Studies Phys      
4  77.8  83.0  89.9 Biology  Math    Psychology
  • Related