【问题标题】:methods for an object with length(class)>1长度(类)> 1的对象的方法
【发布时间】:2018-01-28 22:04:33
【问题描述】:

This question 建议使用methods(class=class(obj)) 提取对象可用的方法列表。

如果在length(class(obj))>1 所在的对象上使用,这会导致很多警告,例如

set.seed(101)
a <- matrix(rnorm(20), nrow = 10)
b <- a + rnorm(length(a))
obj <- lm(b ~ a)

class(obj) 设为c("lm","mlm")methods(class=class(obj))给了

(很多次) 1,并且只使用第一个元素
gsub(name, "", S3reg) 中的警告: 参数“模式”的长度 > 1,并且只使用第一个元素
sub(paste0("\.", class, "$"), "", row.names(info)) 中的警告: 参数 'pattern' 的长度 > 1,并且只使用第一个元素

接着是结果。

似乎 (?) 将 methods(class=...) 应用于 class(obj)last 元素会起作用,但我对替代方案或讨论为什么会(或不是)感兴趣正确...

为了澄清,我希望返回的值是一个(最好是唯一的)字符向量,这样我就可以使用 if ("foo" %in% allmethods(obj)) 之类的东西来测试对象指定方法的可用性...

【问题讨论】:

    标签: r methods


    【解决方案1】:

    这就是你要找的吗?

    sapply(class(obj), function(x) methods(class = x))
    

    请注意,下面的代码会出错,因为参数 generic.function 变为 mlm。它必须是参数class,如上。

    sapply(class(obj), methods)
    Error in .S3methods(generic.function, class, parent.frame()) : 
      no function 'mlm' is visible
    

    【讨论】:

    • 这给出了两个对象的列表; methods() 返回类“MethodsFunction”的稍微复杂的对象。看起来我需要unique(unlist(sapply(class(obj), function(x) as.character(methods(class = x)))))(呃)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多