Rg90
Rg90

Reputation: 581

Sort a list of lists based on an internal list variable in R

I have created an list of lists (let's say parentList) using a vector in R. parentList consists of 100 lists childList1, childList2 and so on. Each such childList consists of a list of elements (grandChildVariable1, grandChildVariable2 and so on). All the lists and variables are unnamed, except the parentList.

I want to sort the parentList based on the second element (grandChildVariable2) of each of the childList. I am able to fetch the values of this variable using parentList[[2]][2]. But I am not very sure how to sort the entire list.

I am currently trying to sort it as follows: sorted_list <- parentList[order(sapply(parentList,'[[',2))] but it is picking up only the second list element childList2 and returns the following error: unimplemented type 'list' in 'orderVector1'.

Upvotes: 0

Views: 704

Answers (2)

Rg90
Rg90

Reputation: 581

I was able to find out the root cause of the unimplemented type 'list' in 'orderVector1' issue. The reason was that some of the childList elements were NULL. When I verified that the parentList contained no NULLs, I was able to get the sorting done properly.

Using sorted_list <- parentList[order(sapply(parentList,'[[',2))] gave the correct output intended and the answer given by Cleland would also do the trick.

Upvotes: 0

Cleland
Cleland

Reputation: 359

I think this should work. It's a bit easier to extract the values first and then use them to order the parent list.

childList1 <- list(grandChildVariable1 = 1,
               grandChildVariable2 = 10)
childList2 <- list(grandChildVariable1 = 1,
               grandChildVariable2 = 30)
childList3 <- list(grandChildVariable1 = 1,
               grandChildVariable2 = 20)
parentList <- list(childList1, childList2,childList3)

x <- sapply(parentList, function(x) x[[2]])

orderedParentList <- parentList[order(x)]
str(orderedParentList)

Upvotes: 1

Related Questions