Re: [R] sorting elements of matrix by row

From: Petr Pikal <petr.pikal_at_precheza.cz>
Date: Fri 27 Oct 2006 - 12:45:15 GMT


Hi

maybe

swap<-function(x) x[,2:1]

can be of some help

sel<-which(mean.data[,1]>mean.data[,2])
dfm<-mean.data
dfm[sel,]<-swap(dfm[sel,])
all.equal(dfm, sorted.mean)

HTH
Petr

On 27 Oct 2006 at 10:10, Vumani Dlamini wrote:

From:           	"Vumani Dlamini" <dvumani@hotmail.com>
To:             	r-help@stat.math.ethz.ch
Date sent:      	Fri, 27 Oct 2006 10:10:27 +0000
Subject:        	[R] sorting elements of matrix by row

> Dear R users,
> I would like to sort elements of a matrix by row and use this ordering
> to also sort another matrix. I am trying to post-order the means of
> components for a mixture model and would also like to do the same for
> the component probabilities. This is what I have tried thus far, but I
> doubt whether its efficient given the number of replications I am
> using:
>
> mean.data <- matrix(rnorm(20,0,1),10,2)
> probs <- runif(10)
> prob.data <- cbind(probs,1-probs)
> sorted.mean <- sorted.prob <- array(0, dim=dim(mean.data))
> for(i in 1:nrow(mean.data)){
> sorted.data[i,] <- mean.data[i,order(mean.data[i,])]
> sorted.prob[i,] <- prob.data[i,order(mean.data[i,])]
> }
>
> Thanks,
> Vumani
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.

Petr Pikal
petr.pikal@precheza.cz



R-help@stat.math.ethz.ch 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. Received on Fri Oct 27 22:49:30 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 27 Oct 2006 - 14:30:12 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.