【问题标题】:Why are empty levels in my factor tabulated after I assign NAs to missing values?为什么在我将 NA 分配给缺失值后,我的因子中的空级别会被制表?
【发布时间】:2018-10-25 21:29:36
【问题描述】:

我有一个数据框 df,其中有一列 foo 包含类型因子的数据:

df <- data.frame("bar" = c(1:4), "foo" = c("M", "F", "F", "M"))

当我使用 str(df$foo) 检查结构时,我得到了:

因子 w/ 3 级 "","F",..: 2 2 2 2 2 2 2 2 2 2 ..

为什么在我的数据中只有 2 个级别时它会报告 3 个级别?


编辑:

似乎有一个缺失值"",我通过分配它NA 来清理它。 当我调用table(df$foo) 时,它似乎仍在计算“缺失值”级别,但没有发现任何情况:

  F M
0 2 2

但是,当我打电话给df$foo 时,我发现它只报告了两个级别:

Levels:  F M

table 怎么可能仍然计算空级别,我该如何解决这种行为?

【问题讨论】:

  • 您的某些单元格中似乎有 MF 的空值。尝试table(df$MF) 获取计数。
  • 我怀疑 MF 列中存在缺失值。您发布的那 4 行是整个框架,还是更多?
  • 谢谢!我检查了是否有空单元格,但没有。如果我做 table(df$MF),我会发现:0,F 220,M 21。那个 0 是从哪里来的?
  • 请不要发布严重保密的图片。我建议您查看this guide,了解如何发布出色的可复制 R MCVEs
  • @Afke,我编辑了我的答案。请永远不要删除原始问题内容,​​因为在编辑之前做出的所有答案都会变得不连贯。相反,请编辑问题并附加任何新的观察结果。这样,您的问题将提供更完整的画面,并且答案仍然是连贯的。

标签: r dataframe


【解决方案1】:

检查您的数据框是否确实没有缺失值,因为看起来确实如此。试试这个:

# works because factor-levels are integers, internally; "" seems to be level 1
which(as.integer(df$MF) == 1)

# works if your missing value is just ""
which(df$MF == "") 

然后,您应该清理数据框以正确反映缺失值。 factor 将处理 NA

df <- data.frame("rest" = c(1:5), "sex" = c("M", "F", "F", "M", ""))
df$sex[which(as.integer(df$sex) == 1)] <- NA

一旦你清理了你的数据,你将不得不删除未使用的级别以避免像table这样的列表计算空级别的出现。

观察这一系列步骤及其输出:

# Build a dataframe to reproduce your behaviour
> df <- data.frame("Restaurant" = c(1:5), "MF" = c("M", "F", "F", "M", ""))
# notice the empty level "" for the missing value
> levels(df$MF)
[1] ""  "F" "M"

# notice how a tabulation counts the empty level;
# this is the first column with a 1 (it has no label because
# there is no label, it is "")
> table(df$MF)

  F M 
1 2 2

# find the culprit and change it to NA
> df$MF[which(as.integer(df$MF) == 1)] <- as.factor(NA)

# AHA! So despite us changing the value, the original factor
# was not updated! I wonder what happens if we tabulate the column...
> levels(df$MF)
[1] ""  "F" "M"

# Indeed, the empty level is present in the factor, but there are
# no occurences!
> table(df$MF)

  F M 
0 2 2 

# droplevels to the rescue:
# it is used to drop unused levels from a factor or, more commonly,
# from factors in a data frame.
> df$MF <- droplevels(df$MF)

# factors fixed
> levels(df$MF)
[1] "F" "M"

# tabulation fixed
> table(df$MF)

F M 
2 2 

【讨论】:

  • 谢谢奥利弗!我检查了我是否缺少值。但是两个顶部代码行都返回:整数(0)。这怎么可能?感谢您的评论,我将编辑问题以删除不良图像。
  • @Afke,我对您的问题和标题提出了相当大的修改,因为我认为其他人可能会感兴趣。看看你是否喜欢它,或者随意编辑它! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多