【问题标题】:convert NA in a column of class factor to 0将类因子列中的 NA 转换为 0
【发布时间】:2015-05-09 13:50:45
【问题描述】:

我有一列类型因子。列中的一些值是 NA 值。 如何将所有这些 NA 值转换为新级别,例如 0 或“OriginallyNA”之类的。

我能够将数字类列的 NA 转换为 0,但无法将类因子列转换为 0。

我的数据

> col1 = c(1,2,3,4,NA)
> col2 = c(6,7,NA,NA,8)
> df = data.frame(col1,col2)
> df
  col1 col2
1    1    6
2    2    7
3    3   NA
4    4   NA
5   NA    8
> df$col2 = as.factor(df$col2)
> class(df$col1)
[1] "numeric"
> class(df$col2)
[1] "factor"

尝试将 NA 值转换为另一个级别,例如 0

> df[is.na(df)] = 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated
> df
  col1 col2
1    1    6
2    2    7
3    3 <NA>
4    4 <NA>
5    0    8
> levels(df$col2)
[1] "6" "7" "8"

要不要把factor列转成数值,把NA值改成0,然后转换后转回factor,如下。有没有更好的办法?

> df$col2 = as.numeric(df$col2)
> df
  col1 col2
1    1    1
2    2    2
3    3   NA
4    4   NA
5    0    3
> df[is.na(df)] = 0
> df
  col1 col2
1    1    1
2    2    2
3    3    0
4    4    0
5    0    3
> df$col2 = as.factor(df$col2)
> df
  col1 col2
1    1    1
2    2    2
3    3    0
4    4    0
5    0    3

【问题讨论】:

  • 为什么要将数值列转换为因子?接下来将如何处理它?另外,0 是一个有意义的数字,用它代替NA 通常是一种不好的做法。
  • 不管怎样,我会做类似df$col2 &lt;- factor(with(df, replace(col2, is.na(col2), 0)))
  • 您可以尝试df$col2 &lt;- addNA(df$col2) 讨论here
  • @PatrickLi,谢谢。您能否将其添加为答案,以便我接受?

标签: r rstudio


【解决方案1】:

如果你使用

df$col2 <- addNA(df$col2)

您将获得一个新的“NA”级别。

【讨论】:

    【解决方案2】:

    警告:

    Warning message:
    In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
      invalid factor level, NA generated
    

    意味着您尝试为一个因子列分配一个在他的级别中不存在的值。您应该先添加缺失级别,然后再分配它,就像您尝试使用 df[is.na(df)] &lt;- 0 所做的那样。

    这里有一个辅助函数,您可以对 data.frame 中的任何因子列执行此操作:

    re_levels <- 
      function(col) {
        if (is.factor(col))  levels(col) <- c(levels(col), "0")
      col
      }
    

    然后将其应用于 data.frame 并将缺失的级别更改为 0 :

    df <- sapply(df,re_levels)
    df[is.na(df)] <-  0
    
    #       col1 col2
    # [1,]    1    1
    # [2,]    2    2
    # [3,]    3    0
    # [4,]    4    0
    # [5,]    0    3
    

    【讨论】:

    • 谢谢我试过了。但是在最后一个命令的末尾,我的 col2 不再是一个因素了吗?我希望它仍然是一个因素,所以我只做一个 df$col2 = as.factor(df$col2) 吗?是否将因子列转换为数字,将NA值更改为0,然后转换后将其转换回因子不好?
    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2015-01-27
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多