Home > Software engineering >  How to order a specific row in a matrix?
How to order a specific row in a matrix?

Time:10-20

    tt<-c(3,2,3,5,3,5,5,4,3,1,5,2,1,5,4,1,3,5,3,3)
    ff<-matrix(tt,nrow=5)
    print(ff)
    print(t(apply(ff,1,sort)))

I want to order the second row only by ascending order not all rows, but it always show me all rows.

CodePudding user response:

You can order assign the order to the second row only:

tt<-c(3,2,3,5,3,5,5,4,3,1,5,2,1,5,4,1,3,5,3,3)
ff<-matrix(tt,nrow=5)
ff[2, ] <- ff[2, ][order(ff[2, ])]
print(ff)
     [,1] [,2] [,3] [,4]
[1,]    3    5    5    1
[2,]    2    2    3    5
[3,]    3    4    1    5
[4,]    5    3    5    3
[5,]    3    1    4    3

CodePudding user response:

ff[2, ] <- sort(ff[2, ])
ff
#      [,1] [,2] [,3] [,4]
# [1,]    3    5    5    1
# [2,]    2    2    3    5
# [3,]    3    4    1    5
# [4,]    5    3    5    3
# [5,]    3    1    4    3
  •  Tags:  
  • r
  • Related