Evaluating matrices without using loops

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Evaluating matrices without using loops

vincent.deluard

Hi R users,

I am trying to set the values of elements of one matrix based on the values of elements of another matrix.

Say I have 2 matrices, y and z.

y = matrix(rnorm(35), ncol=5)
z = matrix(rep(0,35), ncol=5)

I want z[i,j] to take a value  of y[i,j] when y[i,j] is greater than 0, and zero otherwise.

I was able to do it using the following loop:


for(i in 1:7)

        {

        for(j in 1:5)
                {

                if(y[i,j]>0) {
z[i,j]=y[i,j]
                        } else {
                        z[i,j]=0}}
                }

but since my dataset is very large, looping often crashes. Is there a more elegant way I can achieve the same result?

Many thanks!!!
Reply | Threaded
Open this post in threaded view
|

Re: Evaluating matrices without using loops

Richard M. Heiberger
z[y>z]  <-  y[y>z]

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] 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.