r summarise_if 有多个条件

fio*_*eno 6 r mode reduction dplyr summarize

我试图将观察的 df 减少到单个观察(单行)。我想 summarise_if 是带有均值的数字,而 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)
Run Code Online (Sandbox Code Playgroud)

tmf*_*mnk 5

一种可能是:

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

  num str
1   4 toy
Run Code Online (Sandbox Code Playgroud)

或者一个选项,因为dplyr 1.0.0

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

  • 您可以简单地使用“mean(., na.rm = TRUE)”:) (2认同)