[R] filling the matrix row by row in the order from lower to larger elements

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Fri Apr 6 21:49:39 CEST 2012


Hello, everybody!

I have a matrix "input" (see example below) - with all unique entries
that are actually unique ranks (i.e., start with 1, no ties).
I want to assign a value of 100 to the first row of the column that
contains the minimum (i.e., value of 1).
Then, I want to assign a value of 100 to the second row of the column
that contains the value of 2, etc.
The results I am looking for are in "desired.results".
My code (below) does what I need. But it's using a loop through all
the rows of my matrix and searches for a matrix element every time.
My actual matrix is very large. Is there a way to do it more efficiently?
Thank you very much for the tips!
Dimitri

input<-as.matrix(data.frame(a=c(5,1,3,7),b=c(2,6,4,8)))
(input)
desired.result<-as.matrix(data.frame(a=c(100,0,100,0),b=c(0,100,0,100)))
(desired.result)
result<-as.matrix(data.frame(a=c(0,0,0,0),b=c(0,0,0,0)))
for(i in 1:nrow(input)){ # i<-1
  mymin<-i
  mycoords<-which(input==mymin,arr.ind=TRUE)
  result[i,mycoords[2]]<-100
  input[mycoords]<-max(input)
}
(result)

-- 
Dimitri Liakhovitski



More information about the R-help mailing list