【问题标题】:In R how to sort array of R6 objects在R中如何对R6对象数组进行排序
【发布时间】:2018-10-06 19:32:40
【问题描述】:

如何根据自己的函数值或比较函数值对 R6 对象进行排序/排序?

我用矩形做了一个小例子,我想按面积排序:

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))

我想按get_area() 函数给出的区域对array_of_rects 进行排序。

我尝试了不同的方法,例如:

`>.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)

但没有运气(我收到 'x' must be atomic 错误消息)。

我尝试不使用[[1]](例如e1$get_area()),但这也没有用。

四处搜索,但没有找到任何可以让我找到解决方案的东西。

有什么建议吗?提前致谢!

【问题讨论】:

    标签: r r6


    【解决方案1】:

    嗯,灵感来自https://stackoverflow.com/a/23647092/1935801

    我找到了以下漂亮而优雅的解决方案

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

    在一天结束时,可以像使用任何其他类/对象一样使用 R6。

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2019-11-02
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多