Search code examples
rlistiranges

Ordering list object of IRanges to get all elements decreasing


I am having difficulties trying to order a list element-wise by decreasing order...

I have a ByPos_Mindex object or a list of 1000 IRange objects (CG_seqP) from

 C <- vmatchPattern(CG, CPGi_Seq, max.mismatch = 0, with.indels = FALSE)



IRanges object with 27 ranges and 0 metadata columns:
           start       end     width
       <integer> <integer> <integer>
   [1]         1         2         2
   [2]         3         4         2
   [3]         9        10         2
   [4]        27        28         2
   [5]        34        35         2
   ...       ...       ...       ...
  [23]       189       190         2
  [24]       207       208         2
  [25]       212       213         2
  [26]       215       216         2
  [27]       218       219         2

length(1000 of these IRanges)

I then change this to a list of only the start integers (which I want)

CG_SeqP <- sapply(C, function(x) sapply(as.vector(x), "[", 1)) 



[[1]]
 [1]   1   3   9  27  34  47  52  56  62  66  68  70  89 110 112
[16] 136 140 146 154 160 163 178 189 207 212 215 218

(1000 of these)

The Problem happens when I try and order the list of elements using

 CG_SeqP <- sapply(as.vector(CG_SeqP),order, decreasing = TRUE)

I get a list of what I think is row numbers so if the first IRAnge object is 27 I get this...

CG_SeqP[1]
[[1]]
 [1] 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8
[21]  7  6  5  4  3  2  1

So the decreasing has worked but not for my actual list of elements>?

Any suggestions, thanks in advance.


Solution

  • Order returns order of the sequence not the actual elements of your vector, to extract it let us look at a toy example (I am following your idea here) :

    set.seed(1)
    alist1 <- list(a = sample(1:100, 30))
    

    So, If you print alist1 with the current seed value , you will have below results:

    > alist1
    $a
     [1] 99 51 67 59 23 25 69 43 17 68 10 77 55 49 29 39 93 16 44
    [20]  7 96 92 80 94 34 97 66 31  5 24
    

    Now to sort them either you use sort function or you can use order, sort just sorts the data, whereas order just returns the order number of the elements in a sorted sequence. It doesn't return the actual sequence, it returns the position. Hence we need to put those positions in the actual vector using square notation brackets to get the right sorted outcome.

    lapply(as.vector(alist1),function(x)x[order(x, decreasing = TRUE)])
    

    I have used lapply instead of sapply just to enforce the outcome as a list. You are free to choose any command basis your need

    Will return:

    #> lapply(as.vector(alist1),function(x)x[order(x, decreasing = TRUE)])
    #$a
    # [1] 99 97 96 94 93 92 80 77 69 68 67 66 59 55 51 49 44 43 39
    #[20] 34 31 29 25 24 23 17 16 10  7  5
    

    I hope this clarifies your doubt. Thanks