[R] HI

Marc Schwartz marc_schwartz at comcast.net
Tue Sep 16 16:33:12 CEST 2008


on 09/16/2008 09:20 AM Richard.Cotton at hsl.gov.uk wrote:
>>> Does anyone know an easy way to convert all the zero values in a 
>> imported csv table into NA's
>>
>> Depends on the data structure you gave your imported table. In a 
>> single numeric vector (named, say, vec), the syntax is
>>
>> is.na(vec[vec==0]) <- TRUE
> 
> That throws errors for me.  An alternative is 
> vec[vec==0] <- NA
> 
> This also works for data frames, e.g.
> df <- data.frame(a=c(1,2,3,0,3,4,0,5,2), b=c(1,0,0,1,1,0,1,1,0))
> df[df==0] <- NA
> 

The correct syntax using is.na() would be:

> df
  a b
1 1 1
2 2 0
3 3 0
4 0 1
5 3 1
6 4 0
7 0 1
8 5 1
9 2 0


is.na(df) <- df == 0


> df
   a  b
1  1  1
2  2 NA
3  3 NA
4 NA  1
5  3  1
6  4 NA
7 NA  1
8  5  1
9  2 NA


Review ?is.na for correct use.

HTH,

Marc Schwartz



More information about the R-help mailing list