[R] matrix - change values

Duncan Murdoch murdoch at stats.uwo.ca
Thu Dec 14 17:06:24 CET 2006


robert-mcfadden at o2.pl wrote:
> Dear R Users,
> I have a matrix A, and I want to change every value of this matrix if these values are greater than an assuming value. For a vector it is simple, e.g. a<-c(1:10); a[a>5]<-0. 
> Of course, I can change matrix to vector, assign a value then change vector to matrix. But does there exist simpler way?

The same syntax as for a vector:

A[A>5] <- 0

Remember that matrices are just vectors with a dim attribute.  The dim 
attribute is unchanged by this operation:

 > A <- matrix(1:10, 2, 5)
 > A
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
 > A[A>5] <- 0
 > A
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    0    0
[2,]    2    4    0    0    0

Duncan Murdoch



More information about the R-help mailing list