I have a matrix with two columns of the following form:
1 349 1 393 1 392 4 459 3 49 3 32 2 94
I would like to sort this matrix in increasing order based on the first column but I would like to keep the corresponding values in the second column.
The output would look like this:
1 349 1 393 1 392 2 94 3 49 3 32 4 459
There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function.
On the "Modeling" tab of the Data view, click the "Sort by Column" button and choose [Sort Order]. Go back to the Report view and add your matrix, adding row, column, and value fields. If the columns are sorted in the order you wanted, you win!
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
If you want to select all elements of a row or a column, no number is needed before or after the comma, respectively: my_matrix[,1] selects all elements of the first column. my_matrix[1,] selects all elements of the first row.
Read the data:
foo <- read.table(text="1 349 1 393 1 392 4 459 3 49 3 32 2 94")
And sort:
foo[order(foo$V1),]
This relies on the fact that order
keeps ties in their original order. See ?order
.
Creating a data.table
with key=V1
automatically does this for you. Using Stephan's data foo
> require(data.table) > foo.dt <- data.table(foo, key="V1") > foo.dt V1 V2 1: 1 349 2: 1 393 3: 1 392 4: 2 94 5: 3 49 6: 3 32 7: 4 459
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With