dplyr - 使用列名作为函数参数 [英] dplyr - using column names as function arguments
本文介绍了dplyr - 使用列名作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于数据框,我使用 dplyr 来聚合一些列,如下所示.
With a data frame, I'm using dplyr to aggregate some column like below.
> data <- data.frame(a=rep(1:2,3), b=c(6:11))
> data
a b
1 1 6
2 2 7
3 1 8
4 2 9
5 1 10
6 2 11
> data %>% group_by(a) %>% summarize(tot=sum(b))
# A tibble: 2 x 2
a tot
<int> <int>
1 1 24
2 2 27
这是完美的.但是我想为此创建一个可重用的函数,以便可以将列名作为参数传递.
This is perfect. However I want to create a re-usable function for this such that a column name can be passed as argument.
查看此处等相关问题的答案,我尝试了以下操作.
Looking at answers to related questions like here, I tried the following.
sumByColumn <- function(df, colName) {
df %>%
group_by(a) %>%
summarize(tot=sum(colName))
df
}
但是我无法让它工作.
> sumByColumn(data, "b")
Error in summarise_impl(.data, dots) :
Evaluation error: invalid 'type' (character) of argument.
> sumByColumn(data, b)
Error in summarise_impl(.data, dots) :
Evaluation error: object 'b' not found.
>
推荐答案
这可以使用最新的 dplyr
语法(可以在 github):
This can work using the latest dplyr
syntax (as can be seen on github):
library(dplyr)
library(rlang)
sumByColumn <- function(df, colName) {
df %>%
group_by(a) %>%
summarize(tot = sum(!! sym(colName)))
}
sumByColumn(data, "b")
## A tibble: 2 x 2
# a tot
# <int> <int>
#1 1 24
#2 2 27
另一种将 b
指定为变量的方法:
And an alternative way of specifying b
as a variable:
library(dplyr)
sumByColumn <- function(df, colName) {
myenc <- enquo(colName)
df %>%
group_by(a) %>%
summarize(tot = sum(!!myenc))
}
sumByColumn(data, b)
## A tibble: 2 x 2
# a tot
# <int> <int>
#1 1 24
#2 2 27
这篇关于dplyr - 使用列名作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文