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

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Sat Apr 7 00:02:14 CEST 2012

```Yes, that's correct - my matrix has N rows.
Thank you very much, Carl. This works great:

input<-as.matrix(data.frame(a=c(5,1,3,7),b=c(2,6,4,8)))
result<-input
N<-nrow(input)
for (k in 1:N){
foo <- which (input == k,arr.ind=T)
result[k,foo[2]] <-100
}
result[result !=100]<-0

Dimitri

On Fri, Apr 6, 2012 at 5:14 PM, Carl Witthoft <carl at witthoft.com> wrote:
> I think the OP wants to fill values in an arbitrarily large matrix. Now,
> first of all, I'd like to know what his real problem is, since this seems
> like a very tedious and unproductive matrix to produce.  But in the
> meantime,  since he also left out important information, let's assume the
> input matrix is N rows by M columns, and that he wants therefore to end up
> with N instances of "100", not counting the original value of 100 that is
>
> Then either loop or lapply over an equation like (I've expanded things more
> than necessary for clarity
> result<-inmatrix
> for (k in 1:N){
> foo <- which (inmatrix == k,arr.ind=T)
> result[k,foo[2]] <-100
>
> }
>
>
>
> I maybe missing something but this seems like an indexing problem
> which doesn't require a loop at all. Something like this maybe?
>
> (input<-matrix(c(5,1,3,7,2,6,4,8),nc=2))
> output <- matrix(0,max(input),2)
> output[input[,1],1] <- 100
> output[input[,2],2] <- 100
> output
>
> Cheers
>
>
> On Fri, Apr 6, 2012 at 1:49 PM, Dimitri Liakhovitski
> <dimitri.liakhovitski at gmail.com> wrote:
>> 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)
>>
> --
>
> Sent from my Cray XK6
> "Quidvis recte factum, quamvis humile, praeclarum."
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help