Reputation: 571
I want to sort all the columns of a matrix A in R. So far, I am using
apply(A,2,sort),
which gives sorted columns.
But I would also like to have the indexes of each column after sorting.
I tried to use index.return=TRUE
as option of sort
, but I think I can not use it in apply
. How can I get the indexes?
Upvotes: 1
Views: 1050
Reputation: 886948
We can also use index.return = TRUE
, but when we have that, it will return a list
.
lst <- apply(A,2,sort, index.return = TRUE)
If we need to convert it to a 3 column matrix with the column index as well
do.call(rbind, Map(cbind, colInd = seq_along(lst),
lapply(lst, function(x) do.call(cbind, x))))
set.seed(24)
A <- matrix(rnorm(25), 5, 5)
Upvotes: 1