How to sort a list that contains single sub-elements in decreasing order in R?

R ProgrammingServer Side ProgrammingProgramming

Just like a list can have multiple elements, the elements of the list can have multiple sub-elements and the size of those elements may vary as well hence a list with single sub-elements is also possible. If we have such type of list then we can sort that list in decreasing order by using order function but we also need to unlist those elements.

Example

Consider the below list −

 Live Demo

x1<-500
x2<-245
x3<-128
x4<-325
x5<-854
x6<-329
x7<-742
x8<-214
x9<-374
x10<-524
List1<-list(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)
List1

Output

[[1]]
[1] 500
[[2]]
[1] 245
[[3]]
[1] 128
[[4]]
[1] 325
[[5]]
[1] 854
[[6]]
[1] 329
[[7]]
[1] 742
[[8]]
[1] 214
[[9]]
[1] 374
[[10]]
[1] 524

Decreasing the elements of List1 −

Example

List1[order(unlist(List1),decreasing=TRUE)]

Output

[[1]]
[1] 854
[[2]]
[1] 742
[[3]]
[1] 524
[[4]]
[1] 500
[[5]]
[1] 374
[[6]]
[1] 329
[[7]]
[1] 325
[[8]]
[1] 245
[[9]]
[1] 214
[[10]]
[1] 128

Let’s have a look at another example −

Example

 Live Demo

y1<-241
y2<-215
y3<-421
y4<-295
y5<-371
y6<-501
y7<-652
y8<-719
y9<-814
y10<-110
List2<-list(y1,y2,y3,y4,y5,y6,y7,y8,y9,y10)
List2

Output

[[1]]
[1] 241
[[2]]
[1] 215
[[3]]
[1] 421
[[4]]
[1] 295
[[5]]
[1] 371
[[6]]
[1] 501
[[7]]
[1] 652
[[8]]
[1] 719
[[9]]
[1] 814
[[10]]
[1] 110

Decreasing the elements of List2 −

Example

List2[order(unlist(List2),decreasing=TRUE)]

Output

[[1]]
[1] 814
[[2]]
[1] 719
[[3]]
[1] 652
[[4]]
[1] 501
[[5]]
[1] 421
[[6]]
[1] 371
[[7]]
[1] 295
[[8]]
[1] 241
[[9]]
[1] 215
[[10]]
[1] 110
raja
Published on 17-Oct-2020 08:58:50
Advertisements