You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何在dplyr::across右侧调用多个函数计算加权均值与方差

你遇到的报错核心原因是dplyr::across传入多个汇总函数时,需要将所有函数统一包裹在list()参数中,你原来的写法把第二个函数直接放在逗号后,会被识别为across的.names参数,不符合语法要求。

以下是修正后的可运行代码:

library(dplyr)

# 原有数据和自定义函数
dat <- data.frame(Latitude = c(35.8, 35.85, 36.7, 35.2, 36.1, 35.859, 36.0, 37.0, 35.1, 35.2),
                  Longitude = c(-89.4, -89.5, -89.4, -89.8, -90, -89.63, -89.7, -89, -88.9, -89),
                  Period = rep(c("early", "late"), each = 5),
                  ID = c("A", "A", "A", "B", "C", "C", "C", "D", "E", "E"))

weighted.var <- function(x, w = NULL, na.rm = FALSE) {
  if (na.rm) {
    na <- is.na(x) | is.na(w)
    x <- x[!na]
    w <- w[!na]
  }
  
  sum(w * (x - weighted.mean(x, w)) ^ 2) / (sum(w) - 1)
}
weighted.sd <- function(x, w, na.rm = TRUE) sqrt(weighted.var(x, w, na.rm = TRUE))

# 修正后的汇总代码
dat %>% 
  group_by(Period, ID) %>% 
  mutate(weight = 1/n()) %>% 
  group_by(Period) %>% 
  summarise(across(c(Longitude, Latitude),
                   # 多个函数统一放在list中,可直接命名方便生成清晰列名
                   list(
                     mean = ~ weighted.mean(.x, w = weight),
                     sd = ~ weighted.sd(.x, w = weight)
                   ),
                   # 自定义生成的列名格式,{.col}对应原列名,{.fn}对应上面的函数名
                   .names = "{.col}_{.fn}"))

运行后输出结果如下:

# A tibble: 2 × 5
  Period Longitude_mean Longitude_sd Latitude_mean Latitude_sd
  <chr>           <dbl>        <dbl>         <dbl>       <dbl>
1 early           -89.6        0.245          35.9       0.539
2 late            -89.2        0.377          35.8       0.729

如果不需要自定义列名,也可以直接将匿名函数放在list中无需命名,不过命名后生成的列含义更清晰,不需要额外对应指标和列的关系。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:48:01