如何在 R 数据框中用 NA 替换空字符串?

How to replace empty string with NA in R dataframe?

我的第一个方法是在从 csv 中读取数据时使用 na.strings=""。由于某种原因,这不起作用。我也试过:

df[df==''] <- NA

这给了我一个错误:不能使用矩阵或数组进行列索引。

我只试了专栏:

df$col[df$col==''] <- NA

这会将整个数据帧中的每个值都转换为 NA,即使除了空字符串之外还有其他值。

然后我尝试使用 mutate_all:

replace.empty <- function(a) {
    a[a==""] <- NA
}

#dplyr pipe
df %>% mutate_all(funs(replace.empty))

这也会将整个数据框中的每个值都转换为 NA。

我怀疑我的 "empty" 字符串有些奇怪,因为第一种方法没有效果,但我不知道是什么。

编辑(应 MKR 的要求) dput(head(df)) 的输出:

structure(c("function (x, df1, df2, ncp, log = FALSE) ", "{",
"    if (missing(ncp)) ", "        .Call(C_df, x, df1, df2, log)",
"    else .Call(C_dnf, x, df1, df2, ncp, log)", "}"), .Dim = c(6L,
1L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), ""), class = 
"noquote")

我不确定为什么 df[df==""]<-NA 对 OP 不起作用。让我们做一个样本 data.frame 并研究选项。

选项#1: Base-R

df[df==""]<-NA

df
#    One  Two Three Four
# 1    A    A  <NA>  AAA
# 2 <NA>    B    BA <NA>
# 3    C <NA>    CC  CCC

选项#2: dplyr::mutate_allna_if。或者 mutate_if 如果数据框有多种类型的列

library(dplyr)

mutate_all(df, list(~na_if(.,"")))

#if data frame other types of character Then
df %>% mutate_if(is.character, list(~na_if(.,""))) 

#    One  Two Three Four
# 1    A    A  <NA>  AAA
# 2 <NA>    B    BA <NA>
# 3    C <NA>    CC  CCC

玩具资料:

df <- data.frame(One=c("A","","C"), 
                 Two=c("A","B",""), 
                 Three=c("","BA","CC"), 
                 Four=c("AAA","","CCC"), 
                 stringsAsFactors = FALSE)

df
#   One Two Three Four
# 1   A   A        AAA
# 2       B    BA     
# 3   C        CC  CCC

这应该是使用最新语法的方法。此版本仅为字符列将 "" 值设置为 NA。非常方便,因为如果您使用除字符列之外的任何内容,更简单的版本会抛出错误。

# For character columns only, replace any blank strings with NA values
df <- df %>%
  mutate(across(where(is.character), ~ na_if(.,"")))