[英]r summarize_if with multiple conditions
我正在嘗試將觀察的 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)
一種可能是:
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(.)))
我們可以使用mutate_if
和distinct
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
或者從新版本的dplyr
中交叉across/summarise
i1 <- df_finale %>%
summarise_all(is.numeric) %>%
flatten_lgl
df_finale %>%
summarise(across(names(.)[i1], ~ mean(., na.rm = TRUE)),
across(names(.)[!i1], Mode))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.