Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify compare/key method for sorting method in R?

Tags:

sorting

r

In Python you can use the key=... to specify the key used to compare items when sorting. Is there a similar way to do this in R ?

like image 484
Derrick Zhang Avatar asked Feb 22 '23 23:02

Derrick Zhang


1 Answers

Looking at these python key sort examples it seems that there are two thing that you might want a key for in R.

Firstly, applying a function to each element of the vector to be sorted.

x <- c("clementine", "APPLE", "Banana")

In R, you would just nest the function calls.

So rather than

sort(x, key = tolower)

you would just write

sort(tolower(x))

The other case is for sorting data frames by a particular column.

dfr <- data.frame(x = c(1, 4, 2, 5, 3), y = letters[c(5, 2, 1, 4, 3)])

Rather than

sort(dfr, key = function(row) row[2])

you would write

o <- with(dfr, order(y))
dfr[o,]
like image 80
Richie Cotton Avatar answered Feb 25 '23 13:02

Richie Cotton