将特定列中的NA值转换为R中的“”字段

问题描述 投票:1回答:1

我有一个数据集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)]   <- " " 

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

r dplyr na
1个回答
1
投票

我们需要分配相同的列名

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     
© www.soinside.com 2019 - 2024. All rights reserved.