0

Ordering of the data.frame by column index:

> df <- data.frame(5:9, 8:4)
> df
  X5.9 X8.4
1    5    8
2    6    7
3    7    6
4    8    5
5    9    4
> df[order(df[,2]),]
  X5.9 X8.4
5    9    4
4    8    5
3    7    6
2    6    7
1    5    8

or by column name:

> df[order(df[,"X5.9"]),]
  X5.9 X8.4
1    5    8
2    6    7
3    7    6
4    8    5
5    9    4

Is it possible to achieve the same with data.table and order by custom column name or index?

  • 3
    Have a look at `setorder`: `library("data.table") setDT(df) setorder(df, X5.9)` – ddunn801 Oct 24 '16 at 14:14
  • 2
    Or just: `setDT(df, key = 'X5.9')` – Jaap Oct 24 '16 at 14:23
  • I'm guessing no one's showing you the way to do it by column number because it's discouraged/considered a bad idea. See FAQ 1.1 https://rawgit.com/wiki/Rdatatable/data.table/vignettes/datatable-faq.html#j-num – Frank Oct 24 '16 at 15:11
  • If you have the column name stored as a string, `col = "X5.9"`, the idiom would be `df[ order(get(col)) ]` , I guess. – Frank Oct 24 '16 at 15:19

1 Answers1

1

We can use setkey

setkey(setDT(df), X5.9)
akrun
  • 874,273
  • 37
  • 540
  • 662