summarise_all 带有附加参数,即向量
假设我有一个数据框:
df <- data.frame(a = 1:10,
b = 1:10,
c = 1:10)
我想对每一列应用多个汇总函数,因此我使用 dplyr::summarise_all
library(dplyr)
df %>% summarise_all(.funs = c(mean, sum))
# a_fn1 b_fn1 c_fn1 a_fn2 b_fn2 c_fn2
# 1 5.5 5.5 5.5 55 55 55
这非常有用!现在,假设我有一个需要额外参数的函数。例如,此函数计算列中高于阈值的元素数量。 (注意:这是一个玩具示例,而不是真正的函数。)
n_above_threshold <- function(x, threshold) sum(x > threshold)
因此,该函数的工作原理如下:
n_above_threshold(1:10, 5)
#[1] 5
我可以像以前一样将其应用于所有列,但这次传递附加参数,如下所示:
df %>% summarise_all(.funs = c(mean, n_above_threshold), threshold = 5)
# a_fn1 b_fn1 c_fn1 a_fn2 b_fn2 c_fn2
# 1 5.5 5.5 5.5 5 5 5
但是,假设我有一个阈值向量,其中每个元素对应于一列。对于上面的示例,请使用 c(1, 5, 7)
。当然,我不能简单地这样做,因为它没有任何意义:
df %>% summarise_all(.funs = c(mean, n_above_threshold), threshold = c(1, 5, 7))
如果我使用基础 R,我可能会这样做:
> mapply(n_above_threshold, df, c(1, 5, 7))
# a b c
# 9 5 3
有没有办法将此结果作为 dplyr 的一部分来获取code> 管道工作流程就像我在更简单的情况下使用的那样?
Say I have a data frame:
df <- data.frame(a = 1:10,
b = 1:10,
c = 1:10)
I'd like to apply several summary functions to each column, so I use dplyr::summarise_all
library(dplyr)
df %>% summarise_all(.funs = c(mean, sum))
# a_fn1 b_fn1 c_fn1 a_fn2 b_fn2 c_fn2
# 1 5.5 5.5 5.5 55 55 55
This works great! Now, say I have a function that takes an extra parameter. For example, this function calculates the number of elements in a column above a threshold. (Note: this is a toy example and not the real function.)
n_above_threshold <- function(x, threshold) sum(x > threshold)
So, the function works like this:
n_above_threshold(1:10, 5)
#[1] 5
I can apply it to all columns like before, but this time passing the additional parameter, like so:
df %>% summarise_all(.funs = c(mean, n_above_threshold), threshold = 5)
# a_fn1 b_fn1 c_fn1 a_fn2 b_fn2 c_fn2
# 1 5.5 5.5 5.5 5 5 5
But, say I have a vector of thresholds where each element corresponds to a column. Say, c(1, 5, 7)
for my example above. Of course, I can't simply do this, as it doesn't make any sense:
df %>% summarise_all(.funs = c(mean, n_above_threshold), threshold = c(1, 5, 7))
If I was using base R, I might do this:
> mapply(n_above_threshold, df, c(1, 5, 7))
# a b c
# 9 5 3
Is there a way of getting this result as part of a dplyr
piped workflow like I was using for the simpler cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
dplyr 提供了一系列依赖于上下文的函数。一种是
cur_column()
。您可以在summarise
中使用它来查找给定列的阈值。如果当前列名没有已知的阈值,则会默默返回
NA
。这是您可能希望也可能不希望发生的事情。由 reprex 软件包 (v2.0.1) 创建于 2022 年 3 月 11 日
dplyr
provides a bunch of context-dependent functions. One iscur_column()
. You can use it insummarise
to look up the threshold for a given column.This returns
NA
silently if the current column name doesn't have a known threshold. This is something that you might or might not want to happen.Created on 2022-03-11 by the reprex package (v2.0.1)