基本上,当 setMethod
或 (setGeneric
) 中有很多参数时,它的运行速度会非常慢。
这是一个基本示例:
setClassUnion(name = "mNumeric", members = c("missing", "numeric"))
setClass(Class = "classA", representation = representation(ID = "character"))
setGeneric("foo", function(r, i, ..., m = 1, D = 1, U = 999, K = 0.005,
E1 = -5, E2 = 5, E3 = 1, E4 = 1, E5 = 1, E6 = 1,
A1 = -5, A2 = 5, A3 = 1, A4 = 1, A5 = 1, A6 = 1)
{standardGeneric ("foo")})
setMethod(f = "foo",
signature = c(r = "ANY", i = "classA", m = "mNumeric", D = "mNumeric",
U = "mNumeric", K = "mNumeric", E1 = "mNumeric", E2 = "mNumeric",
E3 = "mNumeric", E4 = "mNumeric", E5 = "mNumeric", E6 = "mNumeric",
A1 = "mNumeric", A2 = "mNumeric", A3 = "mNumeric", A4 = "mNumeric",
A5 = "mNumeric", A6 = "mNumeric"),
function(r, i, ..., m, D, U, K, E1, E2, E3, E4, E5, E6, A1, A2, A3, A4, A5, A6)
{print("Function can made it here..")})
#Program hangs after the following code. (at least five minutes)
foo(r = 1, i = new("classA", ID = "ID1"))
我观察到这与类(class)无关。您可以将 numeric
类放入 r
中,它也会执行相同的操作。如果我减少参数的数量,它就会起作用。
我怀疑它尝试“为签名“numeric”、“classA”、“missing”、...找到函数“foo”的继承方法
”,这会导致 R悬挂。 HERE是这个话题的一个很好的讨论。
因为如果我用更少的参数运行相同的代码,它就可以工作:
setGeneric("foo", function(r, i, ..., m = 1, D = 1, U = 999, K = 0.005,
E1 = -5, E2 = 5, E3 = 1, E4 = 1)
{standardGeneric ("foo")})
setMethod(f = "foo",
signature = c(r = "ANY", i = "classA", m = "mNumeric", D = "mNumeric",
U = "mNumeric", K = "mNumeric", E1 = "mNumeric", E2 = "mNumeric",
E3 = "mNumeric", E4 = "mNumeric"),
function(r, i, ..., m, D, U, K, E1, E2, E3, E4)
{print("Function can made it here..")})
foo(r = 1, i = new("classA", ID = "ID1"))
为什么会发生这种情况?任何想法将不胜感激。
最佳答案
我也遇到了类似的问题。 S4似乎是所有可能的签名组合。这会减慢速度。解决方案是签名中的元素尽可能少。
您可以在此处找到详细信息https://stat.ethz.ch/pipermail/r-devel/2015-May/071092.html
关于当 setMethod(或 setGeneric)中的参数太多时,R 会挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25574510/