# [R] sorting a matrix by the column

jim holtman jholtman at gmail.com
Wed Feb 11 14:11:37 CET 2009

```Use 'drop=FALSE'

> temp2 <- matrix(rnorm(10),nc=1)
> rownames(temp2) <- c("a","b","c","d","e","f","g","h","i",'j')
> print(temp2)
[,1]
a -0.5686687
b -0.1351786
c  1.1780870
d -1.5235668
e  0.5939462
f  0.3329504
g  1.0630998
h -0.3041839
i  0.3700188
j  0.2670988
> temp2 <- temp2[order(temp2[,1]),,drop=FALSE]   # PROBLEM IS HERE
> print(temp2)
[,1]
d -1.5235668
a -0.5686687
h -0.3041839
b -0.1351786
j  0.2670988
f  0.3329504
i  0.3700188
e  0.5939462
g  1.0630998
c  1.1780870
>
>

On Wed, Feb 11, 2009 at 1:18 AM,  <markleeds at verizon.net> wrote:
> this is a bad question but I can't figure it out and i've tried. if i sort
> the 2 column
> matrix , temp1, by the first column, then things work as expected. But,
> if I sort the 1 column matrix, temp2, then it gets turned coerced to a
> vector. I realize that I
> need to use drop=FALSE but i've put it in a few different places with no
> success. Thanks.
>
> temp1 <- matrix(rnorm(10),nc=2,nrow=5)
> rownames(temp1) <- c("a","b","c","d","e")
> print(temp2)
> temp1 <- temp1[order(temp1[,1]),]
> print(temp1)
>
> temp2 <- matrix(rnorm(10),nc=1,nrow=5)
> rownames(temp2) <- c("a","b","c","d","e","f","g","h","i")
> print(temp2)
> temp2 <- temp2[order(temp2[,1]),]   # PROBLEM IS HERE
> print(temp2)
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

```