R在dplyr中使用变量列名称汇总函数

时间:2015-08-13 03:48:19

标签: r dplyr

我想根据data.frame中两列中的值计算一个值,但是我希望能够编写一个可以将列名称传递给函数的函数,这样我就可以执行类似的操作分析不同的data.frame s。

以下工作符合要求:

my.data.frame 
    %>% group_by_(.dots = c("label1", "label2")) 
    %>% summarise(disc.score = my.func(col1, col2))

其中my.func是一个期望两个原子数向量作为参数的函数。

我希望能做的是这样的事情:

my.data.frame 
    %>% group_by_(.dots = c("label1", "label2")) 
    %>% summarise(disc.score = my.func(as.name("col1"), as.name("col2")))

但是,这会返回Error: object of type 'symbol' is not subsettablemy.func中被抱怨的特定问题是y_col[x_col <= div],其中x_col是“col1”和y_col是“col2”。

我也尝试使用summarise_()来完成此操作但没有成功。如何在summarise()中调用的函数中使用变量名指定两列?

编辑:

小工作示例:

my.func <- function(x_col, y_col, cutoff) {
    disc.score <- 0
    y_col[x_col <= cutoff]
    return(length(y_col[x_col <= cutoff]))
}

my.data.frame <- data.frame(label = c( rep("A", 5), rep("B", 5)), 
                            x = c(1:10), 
                            y = c(11:20))

# this function call works:
my.data.frame 
    %>% group_by_("label") 
    %>% summarize(disc.score = my.func(x, y, 6))

# this one does not:
my.data.frame 
    %>% group_by_("label") 
    %>% summarize(disc.score = my.func(as.name("x"), as.name("y"), 6))

0 个答案:

没有答案
相关问题