Skip to content
This repository was archived by the owner on Jun 5, 2020. It is now read-only.
This repository was archived by the owner on Jun 5, 2020. It is now read-only.

dplyr: working with character vectors of column names #6

@lionel-

Description

@lionel-

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions