我有一个逻辑类型列 Self_Employed,值为 TRUE 和 FALSE,它缺少值,这意味着说“员工”不是自雇人士。我想在列中归入“缺失”类别
class(df$Self_Employed)
[1] "logical"
levels(df$Self_Employed)
NULL
sum(is.na(df$Self_Employed))
[1] 210
table(df$Self_Employed)
FALSE TRUE
1561 271
将类设为“逻辑”,级别设为 NULL,缺失总和设为 210,表格显示真假总数。
估算缺失首先我转换为因子,然后我估算缺失,但不填充,只显示 NA 和水平只说 TRUE 和 FALSE
df$Self_Employed <- as.factor(df$Self_Employed)
levels(df$Self_Employed)[levels(df$Self_Employed)=="" ] <- "SE_Missing"
levels(df$Self_Employed)
[1] "FALSE" "TRUE"
级别仅显示 True 和 False 并且 is.na 显示相同的 210
df$Self_Employed <- factor(df$Self_Employed,levels=c('FALSE','TRUE',''),labels=c('Yes','No','SE_Missing'))
如何填补缺失的因素
我需要将 True 转换为“是”,将 False 转换为“否”,将 NA 转换为“SE_Missing”
我不认为你需要把专栏变成因素。这是使用虚拟数据集的示例
library(dplyr)
df %>%
mutate(b = case_when(b ~ "Yes",
!b ~ "No",
TRUE ~ "SE_Missing"))
# a b
#1 1 Yes
#2 2 Yes
#3 3 No
#4 4 SE_Missing
#5 5 No
#6 6 SE_Missing
或者使用嵌套ifelse
可以集成在mutate
以及
with(df, ifelse(is.na(b), "SE_Missing", ifelse(b, "Yes", "No")))
#[1] "Yes" "Yes" "No" "SE_Missing" "No" "SE_Missing"
数据
df <- data.frame(a = 1:6, b = c(TRUE, TRUE, FALSE, NA, FALSE, NA))
# a b
#1 1 TRUE
#2 2 TRUE
#3 3 FALSE
#4 4 NA
#5 5 FALSE
#6 6 NA
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句