【问题标题】:pass a varying list of functions to dplyr summarize将不同的函数列表传递给 dplyr 总结
【发布时间】:2020-07-04 09:19:19
【问题描述】:

是否可以以允许函数列表变化的方式将函数列表传递给 dplyr::summarize?我想创建一个整体函数来创建汇总表,但在输出中允许不同的函数组不同 - [编辑:当函数并非全部应用于同一列时]。

我认为这可以通过创建一个整体函数来完成,其中包含 T/F 参数的一组汇总函数(其中 funA=T/F,funB=T/F 是函数列表,用户可以包括来自 funA、funB 或两者的所有函数),但不是如何编写初始列表函数(funA、funB)- 当函数并非全部应用于同一列时。下面是一个关于它的结构的想法。这可能吗,还是有更好的方法来做到这一点?

#Essentially - how would I write a function to selectively include a group of functions (for example either funA = c(n, min, max) or funB=c(n_na, n_neg), or both).  

extract_all <- function(x){

   x %>% summarize(n=n(), 
                   min = min(disp, na.rm=TRUE), 
                   max = max(disp, na.rm=TRUE),
                   n_na = sum(is.na(wt)),  
                   n_neg = sum(vs < 0, na.rm=TRUE))

}
test <- mtcars %>% group_by(cyl) %>% extract_all()

#Does this structure work?
extract_summaries <- function(x, funA=TRUE, funB=FALSE){
  funAls <- list()  #but how do you write n, min, max in here?
  funBls <- list()  #and n_na, n_neg in here

 funls <- append(funAls[funA], funBls[funB])

 summarize(x, funls)
}

#which could be run with:
test <- mtcars %>% group_by(cyl) %>% extract_summaries(funA=TRUE, funB=TRUE)

}

【问题讨论】:

  • @akrun 如果我不尝试以交互方式选择要包含在摘要中的函数,则 extract_all 是代码/输出的示例。 extract_summaries 是一个想法,如果我想选择要包含在摘要中的各种函数(例如,如果 funA=TRUE 则它将包括 funAls 中的所有函数 - 假设这是来自 extract 的 n、min 和 max all; 如果 funB=TRUE 它将(也)包含 funBls 中的所有函数(假设这是 n_na 和 n_neg)。这有意义吗?
  • 好的 - 谢谢。我可以为每个选项(A、B、A+B)使用 ifelse 语句并写出整个汇总部分(它的缺点是多次编写相同的内容)。

标签: r dplyr summarize


【解决方案1】:

这是一种选择

extract_summaries <- function(x, colnm, funA=TRUE, funB=FALSE){
  funAls <- list(n = length, min= min, max = max) 
  funBls <- list(n_na = function(y) sum(is.na(y)), 
              n_neg = function(y) sum(y < 0, na.rm=TRUE)) 
 funls <- append(funAls[funA], funBls[funB])

 x %>% 
      summarise_at(vars({{colnm}}), funls)
}


test <- mtcars %>% 
           group_by(cyl) %>%
           extract_summaries(mpg, funA=TRUE, funB=TRUE)



test
# A tibble: 3 x 6
#    cyl     n   min   max  n_na n_neg
#  <dbl> <int> <dbl> <dbl> <int> <int>
#1     4    11  21.4  33.9     0     0
#2     6     7  17.8  21.4     0     0
#3     8    14  10.4  19.2     0     0

test <- mtcars %>% 
    group_by(cyl) %>% 
    extract_summaries(mpg, funA = FALSE, funB = TRUE)
test
# A tibble: 3 x 3
#    cyl  n_na n_neg
#  <dbl> <int> <int>
#1     4     0     0
#2     6     0     0
#3     8     0     0

【讨论】:

  • 谢谢。当摘要全部针对单个列(例如 mpg)时,这非常有用。不幸的是,我并不总是总结数据集中的同一列。
  • @Jmac 这是一个不同的问题,因为您在代码中的问题是基于如何过滤函数列表
  • @Jmac 关于列规范,帖子中没有提供
  • @akrun 如果不清楚,我深表歉意 - 我添加了一个句子来澄清 summarise 函数包含不同的列;但是,最初提供的示例“extract_all”确实在汇总函数中包含不同的列。我确实尝试过为您的一些 cmets 投票,但它们已被删除。
猜你喜欢
  • 1970-01-01
  • 2017-06-06
  • 2021-01-19
  • 1970-01-01
  • 2017-09-12
  • 2015-03-14
  • 2021-12-15
  • 1970-01-01
相关资源
最近更新 更多