Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

r - How to sort a matrix by all columns

Suppose I have

arr = 2 1 3
      1 2 3
      1 1 2

How can I sort this into the below?

arr = 1 1 2
      1 2 3
      2 1 3

That is, first by column one, then by column two etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The function you're after is order (how I arrived at this conclusion -- my first thought was "well, sorting, what about sort?". Tried sort(arr) which looks like it sorts arr as a vector instead of row-wise. Looking at ?sort, I see in the "See Also: order for sorting on or reordering multiple variables.").

Looking at ?order, I see that order(x,y,z, ...) will order by x, breaking ties by y, breaking further ties by z, and so on. Great - all I have to do is pass in each column of arr to order to do this. (There is even an example for this in the examples section of ?order):

order( arr[,1], arr[,2], arr[,3] ) 
# gives 3 2 1: row 3 first, then row 2, then row 1.
# Hence:
arr[ order( arr[,1], arr[,2], arr[,3] ), ]
#     [,1] [,2] [,3]
#[1,]    1    1    2
#[2,]    1    2    3
#[3,]    2    1    3

Great!


But it is a bit annoying that I have to write out arr[,i] for each column in arr - what if I don't know how many columns it has in advance?

Well, the examples show how you can do this too: using do.call. Basically, you do:

do.call( order, args )

where args is a list of arguments into order. So if you can make a list out of each column of arr then you can use this as args.

One way to do this is is to convert arr into a data frame and then into a list -- this will automagically put one column per element of the list:

arr[ do.call( order, as.list(as.data.frame(arr)) ), ]

The as.list(as.data.frame is a bit kludgy - there are certainly other ways to create a list such that list[[i]] is the ith column of arr, but this is just one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...