【问题标题】:How to handle missing values in a logical type column in R如何处理R中逻辑类型列中的缺失值
【发布时间】:2019-10-01 02:01:59
【问题描述】:

我有一个逻辑类型列 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" 

Levels 只显示 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”

【问题讨论】:

  • 不要忘记 R 中的真/假可以作为 1/0。
  • 你可以先试试format你的专栏,考虑一下:levels(factor(format(c(TRUE, FALSE, NA))))

标签: r


【解决方案1】:

我认为您不需要将此列转换为因子。这是一个使用虚拟数据集的示例

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

【讨论】:

  • ifelse 效果很好,谢谢,Mutate 在 UseMethod("mutate_") 中显示以下错误错误:没有适用于 'mutate_' 的方法应用于“逻辑”类的对象
  • @prem 我不完全确定,因为我没有您的数据,这适用于我发布的示例数据,但是您可以尝试更改 case_when 中的顺序,例如 df %&gt;% mutate(b = case_when(is.na(b) ~ "SE_Missing", b ~ "Yes", TRUE ~ "No")) 或者如果不行你可以在你的帖子里发dput(head(df))。
  • 也可以使用purrr:df %&gt;% modify_at(.,"b",function(x) ifelse(is.na(x),"SE_Mising",ifelse(x,"Yes","No")))
猜你喜欢
  • 1970-01-01
  • 2014-04-27
  • 1970-01-01
  • 2019-03-07
  • 2021-04-11
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 2020-09-24
相关资源
最近更新 更多