DrDom
DrDom

Reputation: 4133

Strange behavior of order function

I have a matrix

m <- structure(c(7.65, 7.01, 3.08, 4.05, 3.85, 3.71, 6.18, 3.83, 7.56, 
                 8.3, 2.63, 2.08, 6.03, 5.87, 4.19, 11.26, 12.58, 8.3, 3.55, 26.59, 
                 7, 2.29, 16, 9.67, 17.14, 32.81, 4, 6, 6, 18.76, 18.04, 15.78, 
                 9.5, 4, 4, 42.96, 15.43, 3.09, 6.04, 4.38, 6.89, 7.87, 7.55, 
                 9.6, 5, 5.48, 5.52, 8.99, 8.42, 10.03, 9.01, 13.67, 5.2, 20.18, 
                 8.45, 7.07, 8.46), .Dim = c(19L, 3L)) 

      [,1]  [,2]  [,3]
[1,]  7.65 26.59  6.04
[2,]  7.01  7.00  4.38
[3,]  3.08  2.29  6.89
[4,]  4.05 16.00  7.87
[5,]  3.85  9.67  7.55
[6,]  3.71 17.14  9.60
[7,]  6.18 32.81  5.00
[8,]  3.83  4.00  5.48
[9,]  7.56  6.00  5.52
[10,]  8.30  6.00  8.99
[11,]  2.63 18.76  8.42
[12,]  2.08 18.04 10.03
[13,]  6.03 15.78  9.01
[14,]  5.87  9.50 13.67
[15,]  4.19  4.00  5.20
[16,] 11.26  4.00 20.18
[17,] 12.58 42.96  8.45
[18,]  8.30 15.43  7.07
[19,]  3.55  3.09  8.46

I want to return order of elements in each line. To do this a call

t(apply(m, 1, order, decreasing = TRUE))

This results in

     [,1] [,2] [,3]
[1,]    2    1    3
[2,]    1    2    3
[3,]    3    1    2
[4,]    2    3    1
[5,]    2    3    1
[6,]    2    3    1
[7,]    2    1    3
[8,]    3    2    1
[9,]    1    2    3
[10,]    3    1    2
[11,]    2    3    1
[12,]    2    3    1
[13,]    2    3    1
[14,]    3    2    1
[15,]    3    1    2
[16,]    3    1    2
[17,]    2    1    3
[18,]    2    1    3
[19,]    3    1    2

But for the third row the order 2 3 1 is expected and so on. What did I miss?

> sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=Russian_Russia.1251  LC_CTYPE=Russian_Russia.1251   
[3] LC_MONETARY=Russian_Russia.1251 LC_NUMERIC=C                   
[5] LC_TIME=Russian_Russia.1251    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] data.table_1.9.2 magrittr_1.5     plyr_1.8.1       Rcpp_0.11.2      reshape2_1.4    
[6] stringi_0.5-5    stringr_1.0.0    tools_3.1.1  

Even simple order returns unxpected results

> order(c(3.08, 2.29, 6.89), decreasing = TRUE)
[1] 3 1 2

Upvotes: 1

Views: 58

Answers (1)

akrun
akrun

Reputation: 887531

You may need rank which returns the ranks of the values

t(apply(-m, 1, rank))

As an example

 v1 <- c(3.08, 2.29, 6.89)
 order(v1, decreasing=TRUE)
 #[1] 3 1 2

It is returning the numeric index of the position of values in the initial vector 'v1' in descending order whereas

 rank(-v1)
 #[1] 2 3 1

rank gives the ranking of the values in the vector.

Upvotes: 2

Related Questions