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"
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.
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.
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.
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().
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)]
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