通过分组计算所有变量的均值的正确方法是什么

What is the correct way to calculate Mean across all variables by grouping

A <- data %>% 
      group_by(Agent) %>%
      summarise(across(EP:Yt.ha),mean)

错误信息是

错误:summarise() 输入 ..2 有问题。 x 输入 ..2 必须是向量,而不是函数。 i 输入 ..2mean。 i 错误发生在组 1 中:Agent = "Hydro"。 运行 rlang::last_error() 看看哪里出错了。

我记得longback是用这种方法做的,但我相信现在我一定是放错了一些函数或代码。有人可以告诉正确的方法吗? EP 到 Yt.ha

有 13 个变量

如果有可重现的代码会更好。

我会建议以下内容:

data <- iris

output <- data %>%
          group_by(species) %>%
          summarise(across(petal.width:sepal.length),mean)

// or 

output <- data %>%
          group_by(species) %>%
          summarise(across(where(is.numeric), mean))

尝试这样的事情(你可以根据条件添加分组):

# install if not already
install.packages("tidyverse", dependencies = T)

# load package
library(tidyverse)

# load data
data(iris)
iris

# find the mean, grouped by species
iris %>% group_by(Species) %>% summarise(across(Petal.Width:Sepal.Length, ~ mean(.x, na.rm = TRUE)))

# alternate way to find the mean for specific cols (using col index numbers)
iris %>% group_by(Species) %>% summarise(across(c(1, 3:4), ~ mean(.x, na.rm = TRUE)))

以防万一你没发现。最后的括号设置不正确。它是这样工作的:

A <- data %>% group_by(Agent) %>% summarise(across(EP:Yt.ha, mean))