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

jim holtman jholtman at gmail.com
Tue Oct 5 18:14:59 CEST 2010


try this:

> matr
     [,1] [,2]
[1,]  0.1  0.5
[2,]  1.0  1.0
[3,]  0.0  2.0
[4,]  2.0  2.0
> result <- apply(matr[-1,], 1, function(.row){
+     ifelse(.row == 2, matr[1,], -999)
+ })
> # data back together
> rbind(matr[1,], t(result))
       [,1]   [,2]
[1,]    0.1    0.5
[2,] -999.0 -999.0
[3,] -999.0    0.5
[4,]    0.1    0.5
>


On Tue, Oct 5, 2010 at 11:54 AM, Paula Fergnani Salvia
<paulafergnani at yahoo.com.ar> wrote:
> 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
>
>
>
>
>
> ______________________________________________
> R-help at r-project.org 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list