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

mp3*_*242 5 r na dplyr

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

df[df==''] <- NA
Run Code Online (Sandbox Code Playgroud)

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

我只试过这个专栏:

df$col[df$col==''] <- NA
Run Code Online (Sandbox Code Playgroud)

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

然后我试着用mutate_all:

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

#dplyr pipe
df %>% mutate_all(funs(replace.empty))
Run Code Online (Sandbox Code Playgroud)

这也将整个数据帧中的每个值转换为NA.

我怀疑我的"空"字符串有些奇怪,因为第一种方法没有效果,但我无法弄清楚是什么.

编辑(应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")
Run Code Online (Sandbox Code Playgroud)

MKR*_*MKR 20

我不确定为什么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
Run Code Online (Sandbox Code Playgroud)

选项#2: 1dplyr :: mutate_all1和na_if.或者,mutate_if如果数据框有多种类型的列

library(dplyr)

mutate_all(df, funs(na_if(.,"")))
Run Code Online (Sandbox Code Playgroud)

要么

#if data frame other types of character Then
df %>% mutate_if(is_character, funs(na_if(.,""))) 

#    One  Two Three Four
# 1    A    A  <NA>  AAA
# 2 <NA>    B    BA <NA>
# 3    C <NA>    CC  CCC
Run Code Online (Sandbox Code Playgroud)

玩具数据:

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
Run Code Online (Sandbox Code Playgroud)


Rya*_*ley 14

这里使用最新的语法(2022 年 2 月)。此版本仅将字符列的“”值设置为 NA。非常方便,因为如果您使用字符列以外的任何内容,更简单的版本会抛出错误。

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