Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of lists in R: sort one lists' value depending on other lists' value

Tags:

list

r

I need some help with sorting a list of lists. Suppose I have a list of children given as following:

a <- list(name = "Ann", age = 9)
b <- list(name = "Bobby", age = 17)
c <- list(name = "Alex", age = 6)

my.list <- list(a, b, c)

I would like to sort their names by their age, so receive the following:

> "Alex" "Ann" "Bobby"
like image 311
Marta Karas Avatar asked Jan 19 '14 13:01

Marta Karas


People also ask

How do you sort a list according to another list?

Approach : Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list.

Can you sort a nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.

Can a list contain a list in R?

The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.

How do I sort a list in R?

Sorting or Ordering a list in R can be done by using lapply() function or using the order() function after converting to a vector using unlist().


1 Answers

a <- list(name = "Ann", age = 9)
b <- list(name = "Bobby", age = 17)
c <- list(name = "Alex", age = 6)

L <- list(a,b,c)
ages <- sapply(L,"[[","age")
names <- sapply(L,"[[","name")
names[order(ages)]
like image 169
Ben Bolker Avatar answered Oct 22 '22 09:10

Ben Bolker