Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list of matrices by the first column

I have a list containing 4 matrices, each with 21 random numbers in 3 columns and 7 rows.

I want to create new list using lapply function in which each matrix is sorted by the first column.

I tried:

#example data
set.seed(1)
list.a <- replicate(4, list(matrix(sample(1:99, 21), nrow=7)))

ordered <- order(list.a[,1])

lapply(list.a, function(x){[ordered,]})

but at the first step the R gives me error "incorrect number of dimensions". Don't know what to do. It works with one matrix, though.

Please help me. Thanks!

like image 661
user3765574 Avatar asked Dec 05 '25 15:12

user3765574


1 Answers

You were almost there - but you would need to iterate through the list to reorder each matrix.

Its easier to do this is one lapply statement

lapply(list.a, function(x) x[order(x[,1]),])

Note that x in the function call represents the matrices in the list.

like image 171
user20650 Avatar answered Dec 07 '25 03:12

user20650



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!