[R] Evaluating matrices without using loops

vincent.deluard vincent.deluard at trimtabs.com
Sun May 9 06:13:49 CEST 2010



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!!!
-- 
View this message in context: http://r.789695.n4.nabble.com/Evaluating-matrices-without-using-loops-tp2155574p2155574.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list