[R] setting a number of values to NA over a data.frame.

Charilaos Skiadas skiadas at hanover.edu
Fri Feb 9 14:40:44 CET 2007


Once again I forgot to reply to the whole list....
On Feb 9, 2007, at 8:39 AM, Charilaos Skiadas wrote:

> On Feb 9, 2007, at 8:13 AM, John Kane wrote:
>
>> The problem is that my dataframe has 1,s in about 50%
>> of the columns and I only want it to apply to a few
>> specified columns. My explanation may not have been
>> clear enough.
>>
>> Using your example,I want all values for tio2 set to 1
>> but not any values in al2o3 whereas zeta[zeta==1]<-NA
>> is also changing al2o3[3] to NA.
>>
>
> You need to index the zeta in zeta==1 in the same way as you do  
> with the zeta outside.
> I think the point is that if you do zeta[,cols][zeta==1] <- NA,  
> then the recycling of NA to obtain the correct number of elements  
> is done based on the elements in zeta[,cols]. But since zeta==1 is  
> a much longer vector than zeta[,cols], then zeta[,cols][zeta==1]  
> has a number of NA objects attached to its end, and hence has now   
> a longer length than the recycled NA that is supposed to replace it.
> But perhaps someone more expert in the internals can explain it in  
> greater detail, if the above is not right. In the mean time, the  
> following seems to work:
>
> > y <- rbinom(20, 1, 1/2)
> > dim(y) <- c(5,4)
> > colnames(y) <- c("one", "two", "three", "four")
> > x <- as.data.frame(y)
> > cl <- c("two", "three")
> > x[,cl][x[,cl]==1] <- NA
> > x
>   one two three four
> 1   0   0    NA    0
> 2   0   0     0    0
> 3   1   0     0    0
> 4   0  NA     0    1
> 5   1   0     0    1
>
>> Thanks
>
> Haris

Haris



More information about the R-help mailing list