[R] change cell values

David Winsemius dwinsemius at comcast.net
Wed Jul 3 23:48:33 CEST 2013


On Jul 3, 2013, at 2:27 PM, JiangZhengyu wrote:

> 
> 
> 
> Dear R experts,
> 
> I have two  matrices (mat1 & mat2) with the same dimension & the cells (row and column) are corresponding to each other.
> 
> I want to change cell values to NA given values of the corresponding cells in mat1 and mat2 are both <1.
> 
> E.g. both mat1[2,3] and mat2[2,3] are <1, I will put mat1[2,3]=NA, and mat2[2,3]=NA; if either mat1[2,3]>=1 or  mat2[2,3]>=1, I will save both cells.
> 
> I tried the code, but not working. Could anyone can help fix the problem?
> 
> mat1[mat1<1&mat2<1]=NA
> mat2[mat1<1&mat2<1]=NA

I beleive the problem is that after the first NA assignment that mat1 will have changed. You need to record the status of both mat1 and mat2 before the change:

> both <- mat1<1&mat2<1  
>  both
      [,1]  [,2]  [,3] [,4]
[1,] FALSE FALSE  TRUE TRUE
[2,]  TRUE FALSE  TRUE TRUE
[3,] FALSE  TRUE FALSE TRUE
> 
> mat1[both] <- NA
> mat2[both] <- NA
> mat1
           [,1]      [,2]     [,3] [,4]
[1,]  1.5599872  2.209537       NA   NA
[2,]         NA -1.144140       NA   NA
[3,] -0.8516326        NA 1.000368   NA
> mat2
          [,1]       [,2]     [,3] [,4]
[1,] 0.8863107 -0.3863741       NA   NA
[2,]        NA  1.3185811       NA   NA
[3,] 1.4487338         NA 1.051689   NA

There is also formalism:

is.na(object) <- logical.vector so it could have been:

is.na(mat1) <- both
is.na(mat2) <- both


> 
> 
>> mat1=matrix(rnorm(12),3)
>> mat2=matrix(rnorm(12),3)
>> mat1
>           [,1]       [,2]       [,3]       [,4]
> [1,] -1.3387075 -0.7142333 -0.5614211  0.1846955
> [2,] -0.7936087 -0.2215797 -0.3686067  0.7328731
> [3,]  0.6505082  0.1826019  1.5577883 -1.5580384
>> mat2
>           [,1]       [,2]       [,3]       [,4]
> [1,]  0.4331573 -1.8086826 -1.7688123 -1.4278934
> [2,] -0.1841451  0.1738648 -1.1086942  1.3065109
> [3,] -1.0827245 -0.4143808 -0.6889405  0.4046203
> 
> 		 	   		  
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list