In R how to sort array of R6 objects

210 Views Asked by At

How can I sort/order R6 objects based on an own function value or a compare function value?

I have made up a little example with rectangles that I would like to sort by their area:

library('R6')

Rectangle <- R6Class(
  "Rectangle",
  public = list(
    initialize = function(width, height) {
      private$width = width
      private$height = height
    },
    get_area = function(){
      private$width*private$height
    }
  ),
  private = list(
    width = NULL,
    height = NULL
  )
)

array_of_rects = c( Rectangle$new(7,3), Rectangle$new(5,2), Rectangle$new(3,4))

I would like to sort array_of_rects by their area given by the get_area() function.

I tried different things like:

`>.Rectangle` <- function(e1, e2) {   e1[[1]]$get_area() > e2[[1]]$get_area() }

`==.Rectangle` <- function(e1, e2) {   e1[[1]]$get_area() == e2[[1]]$get_area() }

sort(array_of_rects)

but without luck (I get an 'x' must be atomic error message).

I tried without the [[1]] (like this e1$get_area()) but this didn't work either.

Searched around but haven't found anything leading me to a solution.

Any suggestions? Thanks in advance!

1

There are 1 best solutions below

0
On

Well, inspired by https://stackoverflow.com/a/23647092/1935801

I found the following nice and elegant solution

area = function(rect){ rect$get_area() }
sorted_rects = array_of_rects[ order( sapply(array_of_rects, FUN = area) ) ]

At the end of the day works with R6 like with any other class/object.