Fabi_92
Fabi_92

Reputation: 571

Sort a matrix by columns with index return

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

Answers (1)

akrun
akrun

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))))

data

set.seed(24)
A <- matrix(rnorm(25), 5, 5)

Upvotes: 1

Related Questions