首页 > 解决方案 > 将特定列中的 NA 值转换为 R 中的“”字段

问题描述

我有一个数据集 df,我从 Excel 读取到 R。出于某种原因,在读取文件时,R 将所有空字段设置为 NA。我该如何扭转这个?我希望将列中的 NA 值转换回空单元格。

                      Subject     Value
                      hello       NA
                      hello       NA
                      hello       NA

我想:

                      Subject     Value
                      hello       
                      hello       
                      hello       

这是输出:

  structure(list(Subject = structure(c(1L, 1L, 1L), .Label = "hello", class = "factor"), 
  Value = c(NA, NA, NA)), class = "data.frame", row.names = c(NA, 
 -3L))

这是我尝试过的:

  df[is.na(df$Value)]   <- " " 

.

我不知道这种结构是否正确 任何帮助表示赞赏。

标签: rdplyrna

解决方案


我们需要分配相同的列名

df$Value[is.na(df$Value)] <- ""

相反,如果我们对整个数据集执行子集,则会导致错误

df1[is.na(df1$Value)]

[.data.frame(df1, is.na(df1$Value))中的错误:选择了未定义的列


tidyverse,我们也可以使用replace_na

library(dplyr)
library(tidyr)
df1 <- df1 %>%
          mutate(Value = replace_na(Value, ""))
df1
#    Subject Value
#1   hello      
#2   hello      
#3   hello     

推荐阅读