Skip to content
Back to formatted view

Raw Message

Message-ID: <48CFC3A8.7020108@comcast.net>
Date: 2008-09-16T14:33:12Z
From: Marc Schwartz
Subject: HI
In-Reply-To: <OF5C84429F.5A43D7CF-ON802574C6.004E0760-802574C6.004E8321@hsl.gov.uk>

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