dplyr:在函数中将多个变量移交给group_by

时间:2019-11-26 20:28:19

标签: r function dplyr

我有一个dplyr::summarize函数。我如何向其交出多个变量?

示例:

myfunction <- function(mydf, grp) {

  library(dplyr)

  grp <- enquo(grp)

  result <- mydf %>% 
    group_by(!! grp) %>% 
    summarise(sum = sum(x))

  result

}

# works
myfunction(df, grp1) 

# doesn't work
myfunction(df, c(grp1, grp2))

1 个答案:

答案 0 :(得分:2)

如果我们传递多个变量,则将其作为字符串传递并使用player1 = 50 player2 = 50 while player1 >= 0 or player2 >= 0: import random slash = random.randint(5, 9) stab = random.randint(1, 15) swing = random.randint(15, 20) heal = random.randint(10, 15) a = [slash, stab, swing] ai = random.choice(a) hit1 = input("Press 1 2 3 or 4") if hit1 == "1": print("You dealt " + str(slash)) player2 = player2 - slash print("Player 2 now has " + str(player2)) if hit1 == "2": print("You dealt " + str(stab)) player2 = player2 - stab print("Player 2 now has " + str(player2)) if hit1 == "3": print("You dealt " + str(swing)) player2 = player2 - swing print("Player 2 now has " + str(player2)) if hit1 == "4": print("You healed by " + str(heal)) player2 = player1 + heal print("Player 1 now has " + str(player1)) hit2 = print("player 2 has dealt " + str(ai)) player1 = player1 - ai print("player1 is now on " +str(player1))

group_by_at

以防万一,我们希望通过OP帖子中所示的组,一种方法是使用myfunction <- function(mydf, grp, xvar) { mydf %>% group_by_at(grp) %>% summarise(sum = sum({{xvar}})) } myfunction(mtcars, "am", mpg) # A tibble: 2 x 2 # am sum # <dbl> <dbl> #1 0 326. #2 1 317. myfunction(mtcars, c("am", "gear"), mpg) # A tibble: 4 x 3 # Groups: am [2] # am gear sum # <dbl> <dbl> <dbl> #1 0 3 242. #2 0 4 84.2 #3 1 4 210. #4 1 5 107. 进行转换并求值(enexpr

!!!
相关问题