João Carvalho
João Carvalho

Reputation: 159

sort a list composed of other lists

I have a list where each entry contains two other lists. The structure of that list (named test) is as follows:

str(test)
List of 10
 $ :List of 2
  ..$ G: int [1:3] 1 3 4
  ..$ T: int 2
 $ :List of 2
  ..$ A: int 4
  ..$ G: int [1:3] 1 2 3
 $ :List of 2
  ..$ G: int [1:2] 1 4
  ..$ T: int [1:2] 2 3
 $ :List of 2
  ..$ C: int [1:2] 1 2
  ..$ G: int [1:2] 3 4

as you can see, in the first entry of the list we have a G appearing three times and a T that occurs only once. And in the second entry we have an A appearing once and a G occurring three times.

I want to order each entry of the list so that the entry with more occurrences appears first i.e. in the second entry of the list, the order should be:

$ :List of 2
..$ G: int [1:3] 1 2 3
..$ A: int 4

I have tried to use test[order(sapply(test,length),decreasing = TRUE)] but this does not work. Any ideas?

The test list can be replicated by doing

list(list(G = c(1,3,4), T = 2), list(A = 4, G = 1:3), list(G = c(1,4), T = c(2,3)), list(C = 1:2, G = 3:4))

Thanks in advance

Upvotes: 0

Views: 28

Answers (2)

s_baldur
s_baldur

Reputation: 33548

lapply(test, \(x) x[order(-lengths(x))])

Upvotes: 1

det
det

Reputation: 5232

library(purrr)
x %>% 
  map(~.x[order(map_int(.x, length), decreasing = TRUE)])

where x is your list.

Upvotes: 1

Related Questions