1
votes

I need to create a function that could group_by and summarise a data frame using the names of its columns. I'm working with dplyr version 0.4.1 (and I cannot update), so it looks like the solutions I've found on the other topics doesn't work...

Here is my example :

data <- data.frame(section=rep(c("A","B"),3), quantity=c(6:11))
#I need to get this result : 
RESULT = data %>% group_by(section) %>% summarise(total=sum(quantity))

I implemented this function, but I got an error :

# function : 
synthetize = function(x,column,measure){
  result = x %>% group_by(column) %>% summarise(total=sum(measure))
}
RESULT2=synthetize(data,column="section",measure="quantity")
RESULT2

I tried eval, get, but it looks like this doesn't help

2
What is the R version you have?akrun
I'm currently working with R 3.2.0Paugre

2 Answers

2
votes

We can convert the string to symbol with rlang::sym and evaluate (!!)

library(tidyverse)
synthetize = function(x, column, measure){
     x %>% 
        group_by_at(column) %>%
        summarise(total=sum(!! rlang::sym(measure)))
   }

synthetize(data, column="section", measure="quantity")
# A tibble: 2 x 2
#  section total
#   <fct>   <int>
#1 A          24
#2 B          27

NOTE: Here we use the OP's same argument type


If we are using older version of dplyr, may be the following would help

library(lazyeval)
synthetize2 = function(x, column, measure){

  x %>% 
     group_by_(column) %>%
     summarise(total = interp(~ sum(v1), v1 = as.name(measure)))


synthetize2(data, column='section', measure='quantity')
0
votes

Another way is with enquo:

library(tidyverse)

synthetize = function(x,column,measure) {

  result = x %>% group_by(!! enquo(column)) %>% summarise(total := sum(!! enquo(measure)))

}

In this case, you wouldn't need to quote the variables:

RESULT2 = synthetize(data, column = section, measure = quantity)

RESULT2

# A tibble: 2 x 2
  section total
  <fct>   <int>
1 A          24
2 B          27

If you don't have access to newest tidyverse, try with get:

library(dplyr)

synthetize = function(x,column,measure) {

  result = x %>% group_by(get(column)) %>% summarise(total := sum(get(measure)))

}