【问题标题】:Convert NA values in a specific column to "" field in R将特定列中的 NA 值转换为 R 中的“”字段
【发布时间】:2020-01-31 01:06:02
【问题描述】:

我有一个数据集 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】:

    我们需要分配相同的列名

    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     
    

    【讨论】:

    • 第一个工作正常。我会在 12 分钟内投票。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多