[R] replace "" to NA.

Marc Schwartz marc_schwartz at me.com
Mon Jan 6 13:57:01 CET 2014


On Jan 6, 2014, at 5:57 AM, vikram ranga <babuawara at gmail.com> wrote:

> Dear All,
> 
> I am bit stuck to a problem of replacing "" to NA.
> I have big data set but here is the toy example:-
> 
> test<-data.frame(
> test1=c("","Hi","Hello"),
> test2=c("Hi","","Bye"),
> test3=c("Hello","",""))
> 
> If the data as in above, I could change all "" to NA by this code:-
> 
> for(i in 1:3){
> for(j in 1:3){
> if(test[j,i]==""){
> test[j,i]=NA
> }
> }
> }
> 
> but the problem arises if data frame has NA at some places
> 
> test<-data.frame(
> test1=c("","Hi","Hello"),
> test2=c("Hi",NA,"Bye"),
> test3=c("Hello","",""))
> 
> the above loop script does not work on this data frame as NA is has
> logical class and does not return TRUE/FALSE.
> 
> Can anyone provide some help?

<snip>


See ?is.na, which is used to test for NA values and is the canonical way to replace values with NA:

> test
  test1 test2 test3
1          Hi Hello
2    Hi            
3 Hello   Bye 


# Where test == "", replace with NA
is.na(test) <- test == ""


> test
  test1 test2 test3
1  <NA>    Hi Hello
2    Hi  <NA>  <NA>
3 Hello   Bye  <NA>


Regards,

Marc Schwartz




More information about the R-help mailing list