Child79
Child79

Reputation: 55

How to sort each column of matrix with R function?

Do you know an R function that sort each column of a matrix without using apply like this:

mat= matrix(c(1,2,0,-7,-4,7,8,3,12,15,23,-21),nrow = 4,ncol = 3)
apply(mat,2,sort)
##
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

Do you also know a R function that return a vector of max of each column of a matrix without using apply like this?

mat2=matrix(c(2,1,0,-7,-4,7,8,3,12,15,23,-21),nrow = 3,ncol = 4)
apply(mat2,2,max)
##
[1]  2  7 12 23

Thanks.

Upvotes: 2

Views: 194

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101373

If you really want to avoid using *apply family, here are several alternatives you can try

  • order method
> `dim<-`(mat[order(col(mat), mat)], dim(mat))
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

> `dim<-`(mat2[order(col(mat2), -mat2)], dim(mat2))[1, ]
[1]  2  7 12 23
  • ave method
> ave(mat, col(mat), FUN = sort)
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23


> unique(ave(mat2, col(mat2), FUN = max))
     [,1] [,2] [,3] [,4]
[1,]    2    7   12   23

> ave(mat2, col(mat2), FUN = max)[1, ]
[1]  2  7 12 23
  • aggregate method
> `dim<-`(unlist(aggregate(mat, list(rep(1, nrow(mat))), sort)[-1]), dim(mat))
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

> unlist(aggregate(mat2, list(rep(1, nrow(mat2))), max)[-1])
V1 V2 V3 V4
 2  7 12 23

Upvotes: 1

AndrewGB
AndrewGB

Reputation: 16856

One possibility for sorting is to use colSort from Rfast:

Rfast::colSort(mat)

     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

We can also use Rfast to get the max for each column:

Rfast::colMaxs(mat2, value = TRUE)

[1]  2  7 12 23

Another option for sorting is to use a simple for loop:

for(i in 1:ncol(mat)){
  mat[,i] <- sort(mat[,i])
}

Could also use a simple for loop to get max:

max <- 0
for(i in 1:ncol(mat2)){
  max[i] <- max(mat2[,i])
}

Upvotes: 2

Related Questions