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 ?
In Python you can use the key=… to specify the key used to compare
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let me extend the excellent answer of Richie.
If you want to get the order of any key,
orderis the function you’re looking at. Building on Richie’s example :If you want specific keys, you have to take a look at ordered factors. Say you want to order observations following the series small, bigger, biggest.
We create a dataframe :
Now you can order this using:
the function
ordered()makes the factor x$V2 an ordered factor according to the levels you specify.order()gives you the order of this ordered vector. That order you can use to sort the dataframex.If you want to sort first on V2 and then on V1, you can give multiple arguments to order as well :
Regarding your question: You don’t need lambda expressions for that, as Richie showed. By the
x[order(tolower(x))]you actually use something equivalent tosort(x, key=lambda x:tolower(x) ).To give another example, say you have a list of vectors and you want to sort on the second value. You would use something like
sort(x, key = lamda x:x[2] )in python, right? In R you’d have to apply a function to your list, and use that in the order command:General method
In R, you construct the key and use the order of that key as indices for the original object. The
orderfunction gives you an easy interface to sort on multiple keys at once. This allows you to construct the most complex sorting keys.