0

My current matrix has 3 columns, the first columns is letters, second is numbers and the third is the first and second columns concatenated together. I am trying to sort the second column in decreasing order and have the other two columns change according to the middle column. This is the code i have but the result is not in decreasing order.

matrix1[order(matrix1[column2], decreasing = TRUE),]

enter image description here

  • 1
    To subset a matrix, you use `matrix[rows, columns]`. So `matrix1[column2]` is putting `column2` in the "rows" spot. Try `matrix1[order(matrix1[, column2], decreasing = TRUE),]`... and I'm assuming `column2` is a variable containing a string with the name of your 2nd column here. If you want to refer to the second column by number, try `matrix1[order(matrix1[, 2], decreasing = TRUE),]`. If none of this is working, please share reproducible data, like `dput(head(matrix1))` , which will by copy/pasteable and include all the relevant structure of your data. – Gregor Thomas Sep 21 '20 at 20:00
  • https://stackoverflow.com/questions/14359726/sort-matrix-according-to-first-column-in-r – Mostafa90 Sep 21 '20 at 20:10

1 Answers1

0

The issue is with matrix1[column2]. You're missing a comma, so you're flattening your 2D matrix to a 1D matrix and the indices are getting messed up. Try matrix1[,"column2"] or matrix1$column2.

cbowers
  • 137
  • 8
  • 1
    If it's actually a matrix `$` won't work... (though I'll admit that's a pretty big 'if' at this point) – Gregor Thomas Sep 21 '20 at 20:04
  • I tried the "column2" part but the values did not go in decreasing order (i attached an image by the question) – ConfusedCoder Sep 21 '20 at 20:16
  • Ah, its because the values in your second column aren't stored as numbers. Notice how they have quotes, and they're in decreasing order by their first digit? You could do the brute force option and use `order(as.numeric(paste(matrix[,"column2"])), decreasing = TRUE)`. If you're planning on actually using them as numbers later on, though, I'd convert it to a data.frame now and save yourself some trouble. – cbowers Sep 21 '20 at 20:21