[R] How to get row index of sorted matrix
jim holtman
jholtman at gmail.com
Tue Jun 24 04:13:20 CEST 2008
Is this what you were looking for:
> x <- scan(textConnection(" 1372.23718 2.277450e+04
+ 74.48333 5.494448e+01
+ 226.63590 6.023199e+02
+ 1947.17564 4.044391e+04
+ 178.79615 3.970006e+02
+ 657.56857 3.396852e+04
+ 251.60519 1.239538e+03
+ 78.53846 7.473607e+01
+ 140.37564 2.395830e+02
+ 358.13718 1.508718e+03"), what=0)
Read 20 items
> closeAllConnections()
> mydata <- matrix(x, ncol=2, byrow=TRUE)
> mydata
[,1] [,2]
[1,] 1372.23718 22774.50000
[2,] 74.48333 54.94448
[3,] 226.63590 602.31990
[4,] 1947.17564 40443.91000
[5,] 178.79615 397.00060
[6,] 657.56857 33968.52000
[7,] 251.60519 1239.53800
[8,] 78.53846 74.73607
[9,] 140.37564 239.58300
[10,] 358.13718 1508.71800
> # top 3 indices
> order(mydata[,2], decreasing=TRUE)[1:3]
[1] 4 6 1
> # print out the ordered data
> mydata[order(mydata[,2], decreasing=TRUE),]
[,1] [,2]
[1,] 1947.17564 40443.91000
[2,] 657.56857 33968.52000
[3,] 1372.23718 22774.50000
[4,] 358.13718 1508.71800
[5,] 251.60519 1239.53800
[6,] 226.63590 602.31990
[7,] 178.79615 397.00060
[8,] 140.37564 239.58300
[9,] 78.53846 74.73607
[10,] 74.48333 54.94448
>
On Mon, Jun 23, 2008 at 9:35 PM, Gundala Viswanath <gundalav at gmail.com> wrote:
> Hi,
>
> How can I get the top-3 index (sorted by "var") of the following
> matrix?
>
>> print(mydata)
> var
> [1,] 1372.23718 2.277450e+04
> [2,] 74.48333 5.494448e+01
> [3,] 226.63590 6.023199e+02
> [4,] 1947.17564 4.044391e+04
> [5,] 178.79615 3.970006e+02
> [6,] 657.56857 3.396852e+04
> [7,] 251.60519 1.239538e+03
> [8,] 78.53846 7.473607e+01
> [9,] 140.37564 2.395830e+02
> [10,] 358.13718 1.508718e+03
>
>
> - Gundala Viswanath
> Jakarta - Indonesia
>
> ______________________________________________
> R-help at 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list