小编mp3*_*242的帖子

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

我的第一种方法是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)

r na dplyr

5
推荐指数
2
解决办法
9859
查看次数

标签 统计

dplyr ×1

na ×1

r ×1