Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dplyr - How to replace empty string with NA in R dataframe?

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: dplyr::mutate_all and na_if. Or mutate_if if data frame got multiple types of columns

library(dplyr)

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

OR

#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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...