为了加快跨多个表生成分组摘要;正如我在dplyr
工作流程中完成的大部分工作一样,我已经起草了一个生成所需指标的简单函数
# Function to generate summary table
generate_summary_tbl <- function(dataset, group_column, summary_column) {
group_column <- enquo(group_column)
summary_column <- enquo(summary_column)
dataset %>%
group_by(!!group_column) %>%
summarise(
mean = mean(!!summary_column),
sum = sum(!!summary_column)
# Other metrics that need to be generated frequently
) %>%
ungroup -> smryDta
return(smryDta)
}
该功能可以根据需要运行:
>> mtcars %>%
... generate_summary_tbl(group_column = am, summary_column = mpg)
# A tibble: 2 x 3
am mean sum
<dbl> <dbl> <dbl>
1 0 17.14737 325.8
2 1 24.39231 317.1
我想,有条件地包含在结果中通过summary_column = mpg
传递的列的名称。
useColName = TRUE
使用useColName = TRUE
调用时,结果应对应于:
>> mtcars %>%
... generate_summary_tbl(group_column = am, summary_column = mpg,
useColName = TRUE)
# A tibble: 2 x 3
am mean_am sum_am
<dbl> <dbl> <dbl>
1 0 17.14737 325.8
2 1 24.39231 317.1
不同之处在于变量名称 _am
中存在 mean_am
后缀,依此类推。
部分,丑陋的解决方案我使用setNames
:
# Function to generate summary table
generate_summary_tbl <-
function(dataset,
group_column,
summary_column,
useColName = TRUE) {
group_column <- enquo(group_column)
summary_column <- enquo(summary_column)
dataset %>%
group_by(!!group_column) %>%
summarise(mean = mean(!!summary_column),
sum = sum(!!summary_column)) %>%
ungroup -> smryDta
if (useColName) {
setNames(smryDta,
c(deparse(substitute(
group_column
)),
paste(
names(smryDta)[2:length(smryDta)], paste0("_", deparse(substitute(
group_column
)))
))) -> smryDta
}
return(smryDta)
}
返回的列名几乎匹配所需的结果。我估计我可以使用一些正则表达式并达到预期的结果。但是,我认为应该提供更有效的解决方案。
mtcars %>%
generate_summary_tbl(group_column = am, summary_column = mpg, useColName = TRUE)
# A tibble: 2 x 3
`~am` `mean _~am` `sum _~am`
<dbl> <dbl> <dbl>
1 0 17.14737 325.8
2 1 24.39231 317.1
答案 0 :(得分:2)
也许使用rename
:
library(tidyverse)
generate_summary_tbl <- function(dataset, group_column, summary_column, useColname = FALSE) {
group_column <- enquo(group_column)
summary_column <- enquo(summary_column)
dataset %>%
group_by(!!group_column) %>%
summarise(
mean = mean(!!summary_column),
sum = sum(!!summary_column)
# Other metrics that need to be generated frequently
) %>%
ungroup -> smryDta
if (useColname)
smryDta <- smryDta %>%
rename_at(
vars(-one_of(quo_name(group_column))),
~paste(quo_name(group_column), .x, sep="_")
)
return(smryDta)
}
mtcars %>% generate_summary_tbl(am, mpg)
# # A tibble: 2 x 3
# am mean sum
# <dbl> <dbl> <dbl>
# 1 0 17.14737 325.8
# 2 1 24.39231 317.1
mtcars %>% generate_summary_tbl(am, mpg, T)
# # A tibble: 2 x 3
# am am_mean am_sum
# <dbl> <dbl> <dbl>
# 1 0 17.14737 325.8
# 2 1 24.39231 317.1