用dplyr中因子变量的模态值替换NA值
假设我有下面的data.frame。我想用最常见的响应取代NA,用dplyr中因子变量的模态值替换NA值,r,dplyr,R,Dplyr,假设我有下面的data.frame。我想用最常见的响应取代NA,a df <- read.table(text = "id result 1 a 2 a 3 a 4 b 5 NA", header = T) dflibrary(dplyr) 图书馆(tidyr) #手动获取最频繁的值和tidyr::replace\u na 最大值%sort(递减=真)%>% 总目(1)%%>%names() df%>%替换(列表(结果=最大值)) #>id结果 #>11A #>2 a
a
df <- read.table(text = "id result
1 a
2 a
3 a
4 b
5 NA", header = T)
dflibrary(dplyr)
图书馆(tidyr)
#手动获取最频繁的值和tidyr::replace\u na
最大值%sort(递减=真)%>%
总目(1)%%>%names()
df%>%替换(列表(结果=最大值))
#>id结果
#>11A
#>2 a
#>3 a
#>4 b
#>5 a
在多个列上动态应用
#使用多个列进行操作-仍在使用函数
大多数%sort(递减=TRUE)%%>%head(1)%%>%names()
}
多个_列id result.x result.y
#>1 a
#>2 a
#>三三a
#>4 b
#> 5 5
多列%>%
突变(跨越(.cols=start_,以(“结果”),.fns=function(x){
if_else(is.na(x),most(x),x)
}))
#>id result.x result.y
#>1 a
#>2 a
#>三三a
#>4 b
#>5 a
由(v2.0.0)于2021年4月24日创建,不短,但可能整齐:
calculate_mode <- function(x) {
uniqx <- unique(x)
uniqx[which.max(tabulate(match(x, uniqx)))]
}
df = df %>%
mutate(result = ifelse(is.na(result), calculate_mode(result), result))
library(dplyr)
df %>%
count(result, sort = TRUE) %>%
slice(1) %>%
rename(mode_value = result) %>%
select(-n) %>%
bind_cols(df, .) %>%
mutate(result = coalesce(result, mode_value))
# id result mode_value
#1 1 a a
#2 2 a a
#3 3 a a
#4 4 b a
#5 5 a a