0

Trying to write a function to sort a matrix by rows. I could write something to loop over the values on a vector of values but couldn't add complexity to make it loop over some matrix.

sww = function(x){
  n <- length(x)

      for(i in 1:(n-1)){

         for (j in (i+1):n) {

        if(x[i] > x[j]){
          tmp = x[i]; x[i] = x[j]; x[j] = tmp
          }


        }

      }
  return(x)
}

does anyone knows how to make it loop over an entire matrix ?

Edit:

By sorting a matrix by rows I meant to have a matrix like:

2 1 4    "Sorted by row"     1 2 4
5 4 0          -->           0 4 5

Thank you

Edit1: I know about the r functions but would like to write my own

  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 10 '20 at 15:50
  • 2
    Is this a homework to implement bubble sort in R or why don't you use R's `sort` or `order` function? What exactly is meant with "sort a matrix by rows"? – Roland Feb 10 '20 at 15:52
  • added an edit about what I meant by sort b rows. Sorry for the confusion ! – Mahamad A. Kanouté Feb 10 '20 at 15:55

1 Answers1

1

Use apply:

m <- matrix(c(2, 5, 1, 4, 4, 0), 2) # test matrix
t(apply(m, 1, sort))
##      [,1] [,2] [,3]
## [1,]    1    2    4
## [2,]    0    4    5

If you really want to loop over the rows:

mm <- m
for(i in 1:nrow(m)) mm[i, ] <- sort(m[i, ])

and, of course, you can replace sort with your own version if you wish.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341