【问题标题】:r summarize_if with multiple conditionsr summary_if 有多个条件
【发布时间】:2020-08-21 14:49:55
【问题描述】:

我正在尝试将观察的 df 减少为单个观察(单行)。 我想 summarise_if 是带有平均值的数字,如果是带有模式的字符串或因子。下面的代码不起作用,但我希望它能给出这个想法。 谢谢!

#data frame
num <- c(1:7)
str <- c("toy","control","play",NA,"give","toy","toy")
df_finale <- data.frame(num,str)

#mode function
Mode <- function(x) {
        ux <- unique(x)
        ux[which.max(tabulate(match(x, ux)))]
}

#df reduction
df_finale <- df_finale %>%
                    summarize_if(is.numeric, mean, na.rm = TRUE) %>%
                    summarize_else_if(!is.numeric, Mode)

【问题讨论】:

    标签: r dplyr mode reduction summarize


    【解决方案1】:

    一种可能是:

    df_finale %>%
     summarise_all(~ if(is.numeric(.)) mean(., na.rm = TRUE) else Mode(.))
    
      num str
    1   4 toy
    

    或者dplyr 1.0.0之后的一个选项:

    df_finale %>%
     summarise(across(everything(), ~ if(is.numeric(.)) mean(., na.rm = TRUE) else Mode(.)))
    

    【讨论】:

    • 太棒了!我在哪里可以将 na.rm = TRUE 放在均值公式中?
    • 你可以简单地使用mean(., na.rm = TRUE) :)
    • 请注意,您选择的模式函数只会返回第一个模式,如果有多个,其中 first 表示它是遇到的第一个字符串
    【解决方案2】:

    我们可以使用mutate_ifdistinct

    library(dplyr)
    library(purrr)
    df_finale %>%
         mutate_if(is.numeric, mean, na.rm = TRUE) %>% 
         mutate_if(negate(is.numeric), Mode) %>%
         distinct
    #   num str
    #1   4 toy
    

    或者用across/summarise从新版dplyr开始

    i1 <- df_finale %>% 
               summarise_all(is.numeric) %>%
               flatten_lgl
    
    df_finale %>% 
         summarise(across(names(.)[i1], ~ mean(., na.rm = TRUE)), 
                   across(names(.)[!i1], Mode))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2013-08-04
      • 2019-01-30
      相关资源
      最近更新 更多