Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting lists according to the order of another list in R

Tags:

r

I have about 20 related lists of 2 (i.e. the elements in position n of each list are related). I now want to sort the values in each of the lists second list (dens) in ascending order and make the same changes to the other lists so that I still have right relation between the lists when finished.

Example:

list_1 <- list(a = c(44,47), dens = c(2331,1644))
list_2 <- list(a=66, dens= 1890)
list_3 <- list(a=c(44,46,48,50), dens=c(8000,1452,1596,7521))
mylist <- list(list_1, list_2, list_3)
names(mylist)<-c("ID_1","ID_2","ID_3")

Needed result:

ID_1:

$ a: num [1:2] 47 44

$ dens: num[1:2] 1644 2331

ID_2:

$ a: num 66

$ dens: num 1890

ID_3:

$ a: num [1:4] 46 48 50 44

$ dens: num[1:4] 1452 1596 7521 8000

Well I would need a dynamic solution for different List lengths. I have tried a few things but everything failed with messages like "not possible for lists" or "input has to be atomic/factor" etc.

Anyone any ideas?

like image 810
Max Mustermann Avatar asked Nov 11 '15 22:11

Max Mustermann


1 Answers

Just use nested lapply calls with an ordering step at the inner level:

> newlist <- lapply(mylist, function(LL) {
               lapply(LL, function(col){ col[order(LL[['dens']]) ]})})
> newlist
$ID_1
$ID_1$a
[1] 47 44

$ID_1$dens
[1] 1644 2331


$ID_2
$ID_2$a
[1] 66

$ID_2$dens
[1] 1890


$ID_3
$ID_3$a
[1] 46 48 50 44

$ID_3$dens
[1] 1452 1596 7521 8000
like image 75
IRTFM Avatar answered Sep 28 '22 15:09

IRTFM