[R] Can a matrix with several rows and columns ...

Sarah Goslee sarah.goslee at gmail.com
Wed Mar 7 21:01:44 CET 2012


On Wed, Mar 7, 2012 at 2:41 PM, Ajay Askoolum <aa2e72e at yahoo.co.uk> wrote:
> Thank you. Yes, I did look at the help but could not get my expressions to
> work.
>
> You used a data.frame with thematrix values I gave. Your solution also works
> when dealing with a matrix (this my be obvious to seasoned R users, but was
> no to me).

Well, if you don't provide a reproducible example, you get replies
that reflect however the respondent interpreted your question.
You can easily fix that by providing a reproducible example.

But nowhere in ?order does it say anything about working only
on data frames, so I'm not sure why you would think that.

Sarah

>> x<-matrix(c(57,91,31,61,16,84,3,99,85,47,21,6,57,91,31,61,16,84,3,99),
>> ncol=5, byrow=TRUE)
>> #order by row
>> order(x[,1])
> [1] 3 1 4 2
>> x[order(x[,1]),]
>      [,1] [,2] [,3] [,4] [,5]
> [1,]   21    6   57   91   31
> [2,]   57   91   31   61   16
> [3,]   61   16   84    3   99
> [4,]   84    3   99   85   47
>> #order by column
>> order(x[1,])
> [1] 5 3 1 4 2
>> x[,order(x[1,])]
>      [,1] [,2] [,3] [,4] [,5]
> [1,]   16   31   57   61   91
> [2,]   47   99   84   85    3
> [3,]   31   57   21   91    6
> [4,]   99   84   61    3   16
>>
>



More information about the R-help mailing list