与Reduce

时间:2018-05-23 19:39:14

标签: r functional-programming s4

我创建了一个维护对象列表的自定义S4类。我希望能够在此S4类中包含的列表中使用Reduce,但是当我实现as.list方法时,该函数不会从Reduce内正确分派。这是一个简单的代表:

myClass <- setClass("myClass", slots=c(data="list"))

setMethod("as.list", "myClass", function(x, ...) x@data)

items <- myClass(data=list(1, 2, 3, 4, 5))

> Reduce(`+`, items@data)
[1] 15 

> Reduce(`+`, as.list(items))
[1] 15

> Reduce(`+`, items) ## fails
Error in as.list.default(x) : no method for coercing this S4 class to a vector

如何在as.list内拨打Reduce时指示R在我的自定义课程上发送?

as.list用于Reduce的正文中,它甚至可以看到我的方法,但它会回到as.list.default并且无法正确发送。

> Reduce
function (f, x, init, right = FALSE, accumulate = FALSE) 
{
    mis <- missing(init)
    len <- length(x)
    if (len == 0L) 
        return(if (mis) NULL else init)
    f <- match.fun(f)
    if (!is.vector(x) || is.object(x)) 
        x <- as.list(x)
...

编辑添加版本信息:

> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7600)

0 个答案:

没有答案