how to use group_by in a function in R

那年仲夏 提交于 2021-02-10 06:16:14

问题


I want to use group_by in a function, the following is my code, 1, 2 work well, so I create a function - 3, while it doesn't work in 4. I don't known how to address this problem, so ask for a help.

# 1 generate variables and dataframe

x <- rnorm(100)
y <- rep(c("A", "B"), 50)
df <- data.frame(y, x)

# 2 group by y

df %>% 
group_by(y) %>% 
summarise(n = n(),
        mean = mean(x),
        sd = sd(x))

# 3 create function

group <- function(df, var1, var2){
df %>% 
group_by(var1) %>% 
summarise(n = n(),
          mean = mean(var2),
          sd = sd(var2))
}

# 4 test function

group(df = df, var1 = y, var2 = x)

# the error is as follows:

"Error in grouped_df_impl(data, unname(vars), drop) : 
Column `var1` is unknown
Called from: grouped_df_impl(data, unname(vars), drop)",

回答1:


You can do:

library(dplyr)
group <- function(df, var1, var2){
  var1 <-  enquo(var1); var2 <-  enquo(var2);
  df %>% 
    group_by(!!var1) %>% 
    summarise(n = n(),
              mean = mean(!!var2),
              sd = sd(!!var2))
}

group(df = df, var1 = y, var2 = x)
### A tibble: 2 x 4
##  y         n    mean    sd
##  <fct> <int>   <dbl> <dbl>
##1 A        50 -0.133  0.866
##2 B        50  0.0770 0.976

For further reference check the link



来源:https://stackoverflow.com/questions/48983225/how-to-use-group-by-in-a-function-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!