Using strings in functions in dplyr

Viewed 133

Using the embrace operator {{ }} is not having the desired effect when I want to use strings inside a dplyr function.

For instance, imagine I want to programatically group_by variables I find in names of data.frame

library(tidyverse)
library(palmerpenguins)

palmerpenguins::penguins %>% 
  select(c(1, 2, 8)) %>% 
  names %>% 
  map(
    function(i)
      penguins %>%
        group_by({{ i }}) %>% 
        tally
  )

returns

[[1]]
# A tibble: 1 x 2
  `"species"`     n
  <chr>       <int>
1 species       344

[[2]]
# A tibble: 1 x 2
  `"island"`     n
  <chr>      <int>
1 island       344

But I want to group_by the variable names passed to map

1 Answers

The {{}} operator is not meant to be used with strings, it's meant for use with symbols. With strings you can either do

palmerpenguins::penguins %>% 
  select(c(1, 2, 8)) %>% 
  names %>% 
  map(
    function(i)
      penguins %>%
      group_by(!!rlang::sym(i)) %>% 
      tally
  )

or

palmerpenguins::penguins %>% 
  select(c(1, 2, 8)) %>% 
  names %>% 
  map(
    function(i)
      penguins %>%
      group_by(.data[[i]]) %>% 
      tally
  )

the latter of which is the currently preferred method by the tidyverse authors.

Related