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
524 views
in Technique[技术] by (71.8m points)

r - Replace missing values (NA) with blank (empty string)

I have a dataframe with an NA row:

 df = data.frame(c("classA", NA, "classB"), t(data.frame(rep("A", 5), rep(NA, 5), rep("B", 5))))
 rownames(df) <- c(1,2,3)
 colnames(df) <- c("class", paste("Year", 1:5, sep = ""))

 > df
   class Year1 Year2 Year3 Year4 Year5
1 classA     A     A     A     A     A
2   <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
3 classB     B     B     B     B     B

I introduced the empty row (NA row) on purpose because I wanted to have some space between classA row and classB row.

Now, I would like to substitute the <NA> by blank, so that the second row looks like an empty row.

I tried:

 df[is.na(df)] <- ""

and

 df[df == "NA"] <- ""

but it didn't work..

Any ideas? Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Another alternative:

df <- sapply(df, as.character) # since your values are `factor`
df[is.na(df)] <- 0

If you want blanks instead of zeroes

> df <- sapply(df, as.character)
> df[is.na(df)] <- " "
> df
     class    Year1 Year2 Year3 Year4 Year5
[1,] "classA" "A"   "A"   "A"   "A"   "A"  
[2,] " "      " "   " "   " "   " "   " "  
[3,] "classB" "B"   "B"   "B"   "B"   "B"  

If you want a data.frame, then just use as.data.drame

> as.data.frame(df)
   class Year1 Year2 Year3 Year4 Year5
1 classA     A     A     A     A     A
2                                     
3 classB     B     B     B     B     B

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

...