如何根据自己的函数值或比较函数值对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))
我想按array_of_rects
函数给出的区域对get_area()
进行排序。
我尝试了其他类似的事情:
`>.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()
),但这也不起作用。
四处搜寻,但没有找到任何可导致我解决的方法。
有什么建议吗?预先感谢!
答案 0 :(得分: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与其他任何类/对象一样都可以使用。