[R] sorting elements of matrix by row
Petr Pikal
petr.pikal at precheza.cz
Fri Oct 27 14:45:15 CEST 2006
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 at hotmail.com>
To: r-help at 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 at 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 at precheza.cz
More information about the R-help
mailing list