[R] Sorting a data frame

Marc Schwartz MSchwartz at medanalytics.com
Wed Jul 16 16:41:24 CEST 2003


On Wed, 2003-07-16 at 08:42, Wayne Jones wrote:
> Hi there R-Helpers, 
> 
> Does anyone know if it is possible to sort a dataframe?
> 
> I.e. Sort alphabetically column 1 ( which has some reocurring elements) then
> sort alphabetically column2 but keeping the order of column 1 constant; 
> much the same way that the sort function works in Excel.
> 
> Regards, 
> 
> Wayne


Wayne,

Use order() to sort the columns. This allows for multi-level keys. See
?order for more information.

Example:

# Create two column df
> df <- data.frame(V1 = c("W","A", "A", "B", ""), V2 = c("E", "M", "B",
"O", "Q"))

# show df unsorted
> df
  V1 V2
1  W  E
2  A  M
3  A  B
4  B  O
5     Q

# now sort df, by V1, then V2
> df[order(df$V1, df$V2), ]
  V1 V2
5     Q
3  A  B
2  A  M
4  B  O
1  W  E

Note that rows 2 and 3 are subsorted on V2.

HTH,

Marc Schwartz




More information about the R-help mailing list