YOLO
YOLO

Reputation: 21739

How to sort a list by values and keys in R?

I am trying to convert a snippet of python code in R, but I don't know how to make it happen.

In python we can do:

## dictionary
a_list = {'red':23, 'black':12,'white':4,'orange':79}

## sort by key
dict(sorted(a_list.items()))
{'black': 12, 'orange': 79, 'red': 23, 'white': 4}

## sort by values
sorted(a_list.items(), key=lambda x: x[1])
[('white', 4), ('black', 12), ('red', 23), ('orange', 79)]

For this question, so, I have a:

a_list <- list(red=23, black=12, white = 4, orange=79)

I want to sort this list in two ways, such that the output is:

output 1 (sorted by keys): list(black=12, orange=79, red=23, white = 4)

output 2 (sorted by values): list(white = 4,black=12, red=23,orange=79)

How can I do this ?

Upvotes: 1

Views: 1261

Answers (1)

akrun
akrun

Reputation: 887651

One option is order on the names of 'a_list' for the first case

a_list[order(names(a_list))]
#$black
#[1] 12

#$orange
#[1] 79

#$red
#[1] 23

#$white
#[1] 4

For second, as the list elements are of length 1, unlist and order on that

a_list[order(unlist(a_list))]
#$white
#[1] 4

#$black
#[1] 12

#$red
#[1] 23

#$orange
#[1] 79

Upvotes: 6

Related Questions