这里有一个选项,通过将多个表达式转换为单个字符串并对其进行解析来将"权重"插值到...
中传递的表达式中
weighted_summarise <- function(数据, weights, ...) {
weights <- rlang::as_string(rlang::ensym(weights))
v1 <- purrr::map_chr(rlang::enexprs(...),
~ stringr::str_replace(rlang::as_label(.x), "\\(",
function(x) stringr::str_c("(", weights, "*")))
eval(rlang::parse_expr(stringr::str_c("数据 %>%
summarise(", stringr::str_c(names(v1), v1, sep = "=",
collapse = ", "), ")")))
}
-测试
> 数据 %>%
weighted_summarise(weights, a = sum(b), c = mean(d))
# A tibble: 1 × 2
a c
<dbl> <dbl>
1 -2.95 1.13
# testing with the original summarise code outside the function
> 数据 %>%
dplyr::summarise(a = sum(weights * b), c = mean(weights * d))
# A tibble: 1 × 2
a c
<dbl> <dbl>
1 -2.95 1.13
数据
数据 <- structure(list(b = c(-0.545880758366027, 0.536585304107612, 0.419623148618683,
-0.583627199210279, 0.847460017311944, 0.266021979364892, 0.444585270360416,
-0.466495123565759, -0.848370043948898, 0.00231194241576697),
d = c(-1.31690812429962, 0.598269112694685, -0.7622143703459,
-1.42909030324076, 0.332244449013422, -0.469060687608488,
-0.334986793584065, 1.53625215550584, 0.609994533253692,
0.51633569843567), weights = 1:10), class = c("tbl_df", "tbl",
"数据.frame"), row.names = c(NA, -10L))