1

而不是手动编写平均

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

我想使用cross,但我无法附加它,因为然后创建了一个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`"))

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

4

1 回答 1

1

我们可以使用rowMeansand 而不是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))
于 2020-07-03T21:29:00.883 回答