Paula- Look at this example. R in this case is your data matrix.
-tgs R<-matrix(sample(0:2,100,replace=T),nrow=10) R[1,]<-round(runif(10),3) f<-function(x){ show(x) y<-x[-1] y[y!=2]<--999 y[y==2]<-x[1] c(x[1],y) } apply(R,2,f) On Tue, Oct 5, 2010 at 11:54 AM, Paula Fergnani Salvia < paulafergn...@yahoo.com.ar> wrote: > Hello, Im 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@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. > [[alternative HTML version deleted]]
______________________________________________ R-help@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.