Venkatesh
Venkatesh

Reputation: 51

how to sort elements in a list in R?

I have a list elements as follows

simple_list <- list(c(3,1,2))

Can anyone please let me know how to get the sort the above list in ascending as well as descending order?

Note:- Please tell me without using the list's unlist()

Upvotes: 5

Views: 14087

Answers (3)

papgeo
papgeo

Reputation: 473

This works for your list:

lapply(simple_list,sort,decreasing=FALSE)
lapply(simple_list,sort,decreasing=TRUE)    

Upvotes: 4

Denis
Denis

Reputation: 12077

result.ordered <- result[order(names(result))]

Upvotes: 4

krlc
krlc

Reputation: 386

It seems you've created a list of vectors, but in this case - a list of one vector.

In case you want to sort that vector, use this:

simple_list <- c(3, 1, 2)
simple_list <- sort(simple_list, decreasing = FALSE)
print(simple_list)

To sort in ascending order, specify decreasing to FALSE, to sort in descending order – set it to TRUE.

Upvotes: 0

Related Questions