a R function for sort a data frame.
On Thu, 31 Mar 2005 22:22:32 -0500, Mario Morales <malfonso at telecom.com.co> wrote :
Is there a R function for sort a data frame by a variable ? I know sort a vector, but I don't know sort a data frame by a column. Can you help me ? the sort() function don't work with data frame.
This is a FAQ, but the answer there looks a bit slim to me: 7.23 How can I sort the rows of a data frame? To sort the rows within a data frame, with respect to the values in one or more of the columns, simply use order(). Here's an example that sorts on two columns:
df <- data.frame(x = sample(1:2, 10, replace=T), y = rnorm(10)) df
x y 1 1 1.50996670 2 2 -0.95740020 3 2 2.35863397 4 1 0.79743294 5 1 -1.75136964 6 2 -2.28762091 7 1 0.29517547 8 2 0.09726887 9 2 0.74852695 10 1 0.48862415
inds <- with(df, order(x, y)) df[inds,]
x y 5 1 -1.75136964 7 1 0.29517547 10 1 0.48862415 4 1 0.79743294 1 1 1.50996670 6 2 -2.28762091 2 2 -0.95740020 8 2 0.09726887 9 2 0.74852695 3 2 2.35863397