将 across(starts_with(), mean) 的结果分配给 R 数据帧

Assigning the result of an across(starts_with(), mean) to the R dataframe

而不是手动写平均

df$average<- (df$a + df$b + df$c)/3

我想使用 across,但我无法附加它,因为那样会创建一个 1x1 数据框 我尝试了这种变化但没有成功。

df$`mean trust` <- df%>% 
    summarise(across(starts_with("Trust"), mean, na.rm = TRUE))

还有

df$`mean trust` <- df%>%
  summarise(across(starts_with("Trust"), 
                   mean, na.rm=TRUE,
                   .names = "`mean trust`"))

如果可能的话,我也更喜欢使用 %<>% 进行分配。有什么建议吗?

我们可以使用 rowMeans 而不是 summarise,它将是 mutate

library(dplyr)
df %>% 
     mutate(meantrust = select(., starts_with("Trust")) %>%
                     rowMeans( na.rm = TRUE))

有了c_across,我们就可以用mean(但是没有向量化)

df %>%
    rowwise %>% 
    mutate(meantrust = mean(c_across(starts_with("Trust")), na.rm = TRUE))

iris

的可重现示例
data(iris)
head(iris) %>%
    rowwise %>%
     mutate(meanSepal = mean(c_across(starts_with("Sepal")), na.rm = TRUE))