2

I wan to get 2 data.frames with difference grouping by column

c("hp", "cyl") %>% 
  tibble() %>% 
  magrittr::set_colnames("vars1") %>% 
  mutate(data = map(vars1,~mtcars %>% as_tibble)) %>% 
  mutate( res = map2(data,vars1,function(x,y){
    x %>% 
      group_by(!!sym(y))
  }))

I can't realise what wrong with !!sym(y)
Thanks for any advices

jyjek
  • 2,627
  • 11
  • 23
  • This is the same issue as the one [here](https://stackoverflow.com/a/51906044/300187). The `!!` evaluates its argument immediately in the surrounding context. In your case, the context is the tibble, which has no column `y`. Ronak's solution of moving the function definition outside mutate helps properly resolve the context. – Artem Sokolov Nov 05 '19 at 17:07
  • 1
    @ArtemSokolov thx for your solution! – jyjek Nov 05 '19 at 17:10

1 Answers1

2

We can use group_by_at which can accept string argument.

library(tidyverse)

c("hp", "cyl") %>% 
  tibble() %>% 
  magrittr::set_colnames("vars1") %>% 
  mutate(data = map(vars1,~mtcars %>% as_tibble)) %>% 
  mutate(res = map2(data,vars1,function(x,y){
    x %>% 
      group_by_at(y)
  }))

# A tibble: 2 x 3
#  vars1 data               res               
#  <chr> <list>             <list>            
#1 hp    <tibble [32 × 11]> <tibble [32 × 11]>
#2 cyl   <tibble [32 × 11]> <tibble [32 × 11]>

The current solution works if we make it as a standalone function and apply it in map2

sym_fun <- function(x, y) {
  x %>%  group_by(!!sym(y))
}

c("hp", "cyl") %>% 
  tibble() %>% 
  magrittr::set_colnames("vars1") %>% 
  mutate(data = map(vars1,~mtcars %>% as_tibble)) %>% 
  mutate(res = map2(data,vars1,sym_fun))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thx for answer. yes, i know about this solution, but I have more complicated case, where needs `rlang` solution – jyjek Nov 04 '19 at 12:49
  • @jyjek I guess `sym` and curly-curly (`{{}}`) are designed to use it in a function. I have updated the answer to show that. – Ronak Shah Nov 04 '19 at 12:54