Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a key,value list in R by value

Tags:

r

key-value

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.

like image 304
Eigenvalue Avatar asked Jun 04 '15 18:06

Eigenvalue


People also ask

How do I sort a list by value in R?

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.

How do I order numerically in R?

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.

How do you sort a vector in ascending order in R?

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.

How do I sort a character in R?

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.


1 Answers

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)]
like image 75
akrun Avatar answered Nov 04 '22 00:11

akrun