fitz_ra wrote > I know this is posted a lot, I've been through about 40 messages reading > how to do this so let me apologize in advance because I can't get this > operation to work unlike the many examples shown. > > I have a 2 row matrix >> temp > [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] > [,9] [,10] > [1,] 17.000 9.000000 26.00000 5.00000 23.00000 21.00000 19.00000 17.00000 > 10.00000 63.0000 > [2,] 15.554 7.793718 33.29079 15.53094 20.44825 14.34443 11.83552 11.62997 > 10.16019 115.2602 > > I want to order the matrix using the second row in ascending order. From > the many examples (usually applied to columns) the typical solution > appears to be: >> temp[order(temp[2,]),] > Error: subscript out of bounds > > However as you can see I get an error here. > > When I run this one line command: >> sort(temp[2,]) > [1] 7.793718 10.160190 11.629973 11.835520 14.344426 15.530939 > 15.553999 20.448249 33.290789 > [10] 115.260192 > > This works but I want the matrix to update and the corresponding values of > row 1 to switch with the sort.
Maybe consider the order function .... orig <- matrix(c(10,20,30,3,1,2), nrow=2, byrow=TRUE) new <-t(apply(orig,1,function(x) x[order(orig[2,])])) > orig [,1] [,2] [,3] [1,] 10 20 30 [2,] 3 1 2 > new [,1] [,2] [,3] [1,] 20 30 10 [2,] 1 2 3 HTH Pete -- View this message in context: http://r.789695.n4.nabble.com/Ordering-a-matrix-by-row-value-in-R2-15-tp4662337p4662340.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ 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.