Search code examples
pythonrheapcode-translation

R equivalent of Python's heapq.heapify()?


Everything is said in the title. I'm looking for the R equivalent of Python's heapq.heapify(). I could not find it, but I hope it exists somewhere.

heapq is a heap queue implementation module and its member function heapify accepts as input a list of objects and returns a heap object containing references to those objects as members of the heap.

EDIT: I cannot use rPython to call Python code within R because the final script will be part of a Shiny app (which barely works with rPython, and does not allow importing modules anyway).


Solution

  • I created this heapify R function by porting the Matlab code found here (that was easier than porting from Python because like R, Matlab uses 1-indexes baseline).

    Just pass an unsorted vector to the function, and specify whether you want min-heapify or max-heapify to be implemented. I compared with Python's heapq.heapify() (which is min-heapify by default) and the results are the same.

    heapify = function(input_vector, min){
    
      # below is the maxheapify algorithm
      # minheapify = maxheapify with sign change at the beginning and at the end
    
      if (min==TRUE){input_vector = - input_vector}
    
        count = length(input_vector)
    
        start = floor(count/2)
    
        while (start >= 1){
          root = start
          theEnd = count
    
          while ((root * 2) <= theEnd){
    
            child = root * 2
    
            if ((child + 1 <= theEnd) & (input_vector[child] < input_vector[child+1])){
              child = child + 1
            }
    
            if (input_vector[root] < input_vector[child]){
    
              temp = input_vector[root]
              input_vector[root] = input_vector[child]
              input_vector[child] = temp
    
              root = child
    
            } else {
              break
            }
    
          }
    
            start = start - 1
        }
    
        if (min==TRUE){input_vector = - input_vector}
    
    output = list(heap=input_vector)
    }
    

    Example:

    in R:

    heapify(c(30,1,1,0,3,3,3,2,14,25,3,10,4,3),min=TRUE)$heap
    [1]  0  1  1  2  3  3  3 30 14 25  3 10  4  3
    

    in Python:

    test = [30,1,1,0,3,3,3,2,14,25,3,10,4,3]
    heapq.heapify(test)
    test
    Out: [0, 1, 1, 2, 3, 3, 3, 30, 14, 25, 3, 10, 4, 3]