zxzak zxzak - 8 days ago 8
R Question

R replace all particular values in a data frame

Having a data frame, how do I go about replacing all particular values along all rows and columns. Say for example I want to replace all empty records with NA's (without typing the positions):

df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))

A B
1 12
2 xyz
3 jkl 100


Expected result:

A B
1 NA 12
2 xyz NA
3 jkl 100


Thank You.

Answer

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100