[R] Question about assigning values in a matrix, conditional on column first row; how to do the loop.

Paula Fergnani Salvia paulafergnani at yahoo.com.ar
Tue Oct 5 17:54:24 CEST 2010


Hello, I’m new at programming and I will greatly appreciate if you can help me with this. 


I have a very large matrix (hundreds of rows and columns), with the first raw filled with different numbers (between 0 and 1). The rest of the matrix is filled with values 0, 1, 2. What I need is to replace the values in the matrix (except the first row will has to remain intact). In each column I have to replace value 2 for the value of the first row. Also, I want to replace the values 0 and 1 by -999. I was able to write the loop for a vector but I do not know how to expand the loop to the matrix. 

Please see these examples

For a vector I did this and it works

> V = c(0.1,1,0,2)
> V
[1] 0.1 1.0 0.0 2.0

> for (i in 2:length(V)){if(V[i]==2)V[i]=V[1]
+                                 else (V[i]=-999)}

> V
[1]    0.1 -999.0 -999.0    0.1

For a matrix I could not perform the task. Here it is an example of a small matrix and the expected result, but the original has more rows and columns.

> matr <- matrix(c(0.1,1,0,2,0.5,1,2,2), nrow=4, ncol=2)
> matr
     [,1] [,2]
[1,]  0.1  0.5
[2,]  1.0  1.0
[3,]  0.0  2.0
[4,]  2.0  2.0

> matr.expectedresult= matrix(c(0.1,-999,-999,0.1,0.5,-999,0.5,0.5), nrow=4, ncol=2)
> matr.expectedresult
       [,1]   [,2]
[1,]    0.1    0.5
[2,] -999.0 -999.0
[3,] -999.0    0.5
[4,]    0.1    0.5

Thank you very much

Paula







More information about the R-help mailing list