Given a list animals, call it m, which contains
$bob
[1] 3
$ryan
[1] 4
$dan
[1] 1
How can I sort this guy by the numerical value? Basically I'd like to see my code look like this
m=sort(m,sortbynumber)
$ryan
[1] 4
$bob
[1] 3
$dan
[1] 1
I can't figure this out unfortunately. Seems like a simple solution.
R Sort List Values by Ascending. By using lapply() function you can sort the values of the list in R by ascending order, this function takes a list as an argument and the sort keyword. After applying the sort on the list it returns the ordered list.
order() in R The numbers are ordered according to its index by using order(x) . Here the order() will sort the given numbers according to its index in the ascending order.
sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a “decreasing” parameter to the sort function.
To sort a vector alphabetically in R using the sort() function that takes a vector as an argument and returns an alphabetically ordered value for the character vector and ascending order for numeric. Use c() function to create vector. To sort vectors by descending order use decreasing=TRUE param.
You can try order
m[order(-unlist(m))]
#$ryan
#[1] 4
#$bob
#[1] 3
#$dan
#[1] 1
Or a slightly more efficient option would be to use decreasing=TRUE
argument of order
(from @nicola's comments)
m[order(unlist(m), decreasing=TRUE)]
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