tidyverse / tidyeval

A guide to tidy evaluation
https://tidyeval.tidyverse.org
55 stars 21 forks source link

dplyr: working with character vectors of column names #6

Open lionel- opened 6 years ago

lionel- commented 6 years ago

From @jennybc:

library(tidyverse)

pick_me_strings <- c("mpg", "gear")

mtcars %>% 
  select(one_of(pick_me_strings)) %>% 
  glimpse()
#> Observations: 32
#> Variables: 2
#> $ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19....
#> $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, ...

mtcars %>% 
  select_at(pick_me_strings) %>% 
  glimpse()
#> Observations: 32
#> Variables: 2
#> $ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19....
#> $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, ...

pick_me_exprs <- rlang::exprs(mpg, gear)

mtcars %>% 
  select(!!!pick_me_exprs) %>% 
  glimpse()
#> Observations: 32
#> Variables: 2
#> $ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19....
#> $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, ...

Things can get confusing when trying to apply select() knowledge to other verbs:

library(tidyverse)

df <- tibble(
  name = c("abby", "bea", "curt", "doug"),
  happy = c(TRUE, FALSE, FALSE, TRUE),
  awake = c(FALSE, FALSE, TRUE, TRUE),
)

filter_me_strings <- c("happy", "awake")

df %>% 
  filter(one_of(filter_me_strings))
#> Error in filter_impl(.data, quo): Evaluation error: No tidyselect variables were registered.

df %>% 
  filter_at(filter_me_strings)
#> Error in apply_filter_syms(.vars_predicate, syms, .tbl): argument ".vars_predicate" is missing, with no default

df %>% 
  filter(!!!filter_me_strings)
#> Error in filter_impl(.data, quo): Evaluation error: operations are possible only for numeric, logical or complex types.

filter_me_exprs <- rlang::exprs(happy, awake)

df %>% 
  filter(!!!filter_me_exprs)
#> # A tibble: 1 x 3
#>   name  happy awake
#>   <chr> <lgl> <lgl>
#> 1 doug  TRUE  TRUE
lionel- commented 6 years ago

From Jenny about string metaprogramming:

I also think it’s very helpful to juxtapose expression- and string-based solutions to the same problem.