I have two dataframes with the same number of columns. I'm writing a function that takes the two dataframes and an integer n as arguments and needs to sort each dataset by its respective nth column. Essentially, how can I sort a dataframe by it's nth column without having to know the label of that column?
Asked
Active
Viewed 1,853 times
1 Answers
6
A slight modification to an answer here: How to sort a dataframe by column(s)?
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
n <- 2
dd[ order(dd[[n]]), ]
b x y z
1 Hi A 8 1
3 Hi A 9 1
4 Low C 9 2
2 Med D 3 1
Alternatively, you could just look up the label with colnames(dd)[n]
and use that with any of the methods in the above link.

Community
- 1
- 1

Ari B. Friedman
- 71,271
- 35
- 175
- 235