[Rd] vector labels are not permuted properly in a call to sort() (R 2.1)

Liaw, Andy andy_liaw at merck.com
Tue Oct 4 19:51:11 CEST 2005


The `problem' is that sort() does not doing anything special when given
a matrix: it only treat it as a vector.  After sorting, it copies
attributes of the original input to the output.  Since dimnames are
attributes, they get copied as is.

Try:

> y <- matrix(8:1, 4, 2, dimnames=list(LETTERS[1:4], NULL))
> y
  [,1] [,2]
A    8    4
B    7    3
C    6    2
D    5    1
> sort(y)
  [,1] [,2]
A    1    5
B    2    6
C    3    7
D    4    8

Notice the row names stay the same.  I'd argue that this is the correct
behavior.

Andy


> From: Greg Finak
> 
> Not sure if this is the correct forum for this, but I've 
> found what I  
> would consider to be a potentially serious bug to the 
> unsuspecting user.
> Given a numeric vector V with class labels in R,  the following calls
> 
> 1.
>  > sort(as.matrix(V))
> 
> and
> 
> 2.
>  >as.matrix(sort(V))
> 
> produce different ouput. The vector is sorted properly in 
> both cases,  
> but only 2. produces the correct labeling of the vector. The call to  
> 1. produces a vector with incorrect labels (not sorted).
> 
> Code:
>  >X<-c("A","B","C","D","E","F","G","H")
>  >Y<-rev(1:8)
>  >names(Y)<-X
>  > Y
> A B C D E F G H
> 8 7 6 5 4 3 2 1
>  > sort(as.matrix(Y))
>    [,1]
> A    1
> B    2
> C    3
> D    4
> E    5
> F    6
> G    7
> H    8
>  > as.matrix(sort(Y))
>    [,1]
> H    1
> G    2
> F    3
> E    4
> D    5
> C    6
> B    7
> A    8
> 
> Cheers,
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
>



More information about the R-devel mailing list