How to replace empty string with NA in R dataframe?

半世苍凉 提交于 2019-11-27 17:06:13

问题


My first approach was to use na.strings="" when I read the data in from a csv. This doesn't work for some reason. I also tried:

df[df==''] <- NA

Which gave me an error: Can't use matrix or array for column indexing.

I tried just the column:

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

This converts every value in the entire dataframe to NA, even though there are values besides empty strings.

Then I tried to use mutate_all:

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

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

This also converts every value in the entire dataframe to NA.

I suspect something is weird about my "empty" strings since the first method had no effect but I can't figure out what.

EDIT (at request of MKR) Output of 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")

回答1:


I'm not sure why df[df==""]<-NA would have not worked for OP. Let's take a sample data.frame and investigate options.

Option#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

Option#2: 1dplyr::mutate_all1 and na_if. Or mutate_if if data frame got multiple types of columns

library(dplyr)

mutate_all(df, funs(na_if(.,"")))

OR

#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

Toy Data:

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


来源:https://stackoverflow.com/questions/51449243/how-to-replace-empty-string-with-na-in-r-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!