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 ?
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,]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With