【问题标题】:Assigning the result of an across(starts_with(), mean) to the R dataframe将 cross(starts_with(), mean) 的结果分配给 R 数据框
【发布时间】:2020-10-24 14:52:27
【问题描述】:

而不是手动编写平均

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`"))

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

【问题讨论】:

    标签: r dplyr summarize across


    【解决方案1】:

    我们可以使用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))
    

    【讨论】:

    • 每当我想到使用c_across 时,似乎就是在浪费资源。我不确定这对dplyr 是否有价值。 +1
    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 2016-05-21
    相关资源
    最近更新 更多