1

I see the answers on this website, but it can not solve my problem.

What I want is that use dynamic variable names both on LHS and RHS within summarize.

This is a simple example to show what I have tried:

why I use paste0('carb') not use carb directly is that on the position(paste0('carb')) is a dynamic variable like this paste0('temp', n) and n is a series of numbers in my real situation.


library(dplyr)
sumay1 <- mtcars %>% group_by(cyl) %>% 
  summarise(!!paste0('carb', 100) := mean(paste0('carb'), na.rm = T))

sumay2 <- mtcars %>% group_by(cyl) %>% 
  summarise(!!paste0('carb', 100) := mean(sym('carb'), na.rm = T))

sumay3 <- mtcars %>% group_by(cyl) %>% 
  summarise(!!paste0('carb', 100) := mean({{paste0('carb')}}, na.rm = T))

zhiwei li
  • 1,635
  • 8
  • 26

1 Answers1

2

In the second case, we need to evaluate (!!) the symbol

library(dplyr)
mtcars %>% 
   group_by(cyl) %>% 
   summarise(!!paste0('carb', 100) := mean(!!sym('carb'), na.rm = TRUE))
# A tibble: 3 x 2
#    cyl carb100
#* <dbl>   <dbl>
#1     4    1.55
#2     6    3.43
#3     8    3.5 

The {{}} is mainly used within a function where we pass unquoted arguments and it is equivalent to enquo + !!

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, it really works. I don't understand why use `!!` and `variable names` on the LHS but use both `!!` and `sym()` with `variable names` on the RHL. Is that because of `summarise()` and `mean()`? – zhiwei li May 24 '20 at 02:48
  • @zhiweili We are using `:=` and the `!!` is to evaluate the variable names, In the RHS, the evaluation is to get the value of the column – akrun May 24 '20 at 18:15