[R] matrix Manipulation...

Sarah Goslee sarah.goslee at gmail.com
Wed May 25 20:57:50 CEST 2011


It's very easy to do in two steps:
> testmat <- matrix(c(.2, .3, 1, -1, 3, .2, .4, 5, .5, -1), byrow=TRUE, nrow=2)
> testmat
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.2  0.3    1 -1.0    3
[2,]  0.2  0.4    5  0.5   -1
> testmat[testmat >= 1] <- 1
> testmat[testmat < 0] <- 0
> testmat
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.2  0.3    1  0.0    1
[2,]  0.2  0.4    1  0.5    0

This is pretty basic. You might want to read one of the many excellent
intro to R guides, especially the subsetting section.

Sarah

On Wed, May 25, 2011 at 2:51 PM, Jim Silverton <jim.silverton at gmail.com> wrote:
> Hello everyone,
>
>
> I have a  2 x 5 matrix: say
>
> 0.2   0.3   1   -1   3
> 0.2.  0.4   5   0.5  -1
>
> I want to replace all the values greater than or equal to 1 with 1 and those
> less than or equal to 0 with 0. So I should end up with a mtrix looking
> like:
>
> 0.2   0.3   1   0   1
> 0.2.  0.4   1   0.5  0
>
> Any ideas how to do this?
>
> --
> Thanks,
> Jim.


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list