user1030497
user1030497

Reputation: 193

How to sort a dataframe by the nth column in R

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?

Upvotes: 3

Views: 2236

Answers (2)

Samuel D analyst
Samuel D analyst

Reputation: 61

Here is the dplyr solution:

test_df <- 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

test_df <- test_df %>% 
  arrange(.[[n]])

Upvotes: 1

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

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.

Upvotes: 6

Related Questions