本文介绍了R实现组泛型Ops()以实现S3对象的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在R中创建一个S3类,我希望能够对其进行比较,例如"<"">""==".与其将我阅读的Ops()来做到这一点,但是我还没有找到任何很好的例子.

I am creating an S3 class in R for which I would like to be able to do comparisons like "<", ">", and "==". Rather than implement each of these separately from what I've read about group generics I believe I can do so using Ops() but I haven't found any good examples of how to do this.

可以说,对于myClass,我可以创建一个as.integer.myClass()函数,并且要比较ab,我可以先将其转换为整数:

Suffice it to say that for myClass I can create an as.integer.myClass() function, and that to compare a and b I could just convert to integer first:

if(as.integer(a) < as.integer(b)) foo

这完全可以,但是我宁愿写

This totally works, but I would so much rather write

if(a < b) foo

我以为这可以用,但是没有用

I thought this would work, but it doesn't:

Ops.myClass <- function(e1, e2) {
  Ops(as.integer(e1), as.integer(e2))
}
a < b
Error in (function (classes, fdef, mtable)  :
 unable to find an inherited method for function ‘Ops’ for signature ‘"integer", "integer"’ 

有帮助吗?谢谢!

推荐答案

请注意,Ops(my, my)失败并出现相同的错误-您不是在调用Ops,而是调用Ops组成员的泛型.因此,获取泛型并在转换后的类型上调用

Note that Ops(my, my) fails with the same error -- you're not invoking Ops, but a generic that is a member of the Ops group. So get the generic and invoke it on the transformed types

Ops.my = function(e1, e2) get(.Generic)(as.integer(e1), as.integer(e2))

使用

> my1 = structure(1:5, class="my")
> my2 = structure(5:1, class="my")
> my1 > my2
[1] FALSE FALSE FALSE  TRUE  TRUE
> my1 == my2
[1] FALSE FALSE  TRUE FALSE FALSE

这篇关于R实现组泛型Ops()以实现S3对象的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!