【问题标题】:Discrepancy between 'UseMethod' and 'methods'“UseMethod”和“methods”之间的差异
【发布时间】:2020-09-15 10:56:39
【问题描述】:

自 R 3.6 起,从附加环境调用 S3 函数时出现错误(见下文)。我错过了什么吗?提前感谢您的任何提示。

最好, G

env <- namespace::makeNamespace('testspace')
de <- 'doit <- function (x, ...) UseMethod("doit",x)
       doit.default <- function(x,...) print(x)
       doit.character <- function(x,...) cat(x,"\n")'

eval(parse(text=de),envir=env)
base::namespaceExport(env, ls(env))
attachNamespace('testspace')

methods("doit")
# [1] doit.character doit.default
doit("lala")
# Error in UseMethod("doit", x) :
#  no applicable method for 'doit' applied to an object of class "character"

【问题讨论】:

    标签: r r-s3


    【解决方案1】:

    经过大量挠头(变粗)后,解决方案:

    nn <- 'testspace'
    ns <- namespace::makeNamespace(nn)
    setNamespaceInfo(ns,"S3methods",matrix(NA_character_,0L,4L)) # see comment below.
    
    de <- 'doit <- function (x, ...) UseMethod("doit",x)
           doit.default <- function(x,...) print(x)
           doit.character <- function(x,...) cat(x,"\n")
           .S3method("doit","character",doit.character)
           .S3method("doit","default"  ,doit.default)'
    eval(parse(text=de),envir=ns)
    
    base::namespaceExport(ns, ls(ns))
    attachNamespace(nn)
    
    methods("doit")
    # [1] doit.character doit.default
    doit("lala")
    # lala
    doit(pi)
    # [1] 3.141593
    

    请注意,namespace::makeNamespace 似乎创建了一个只有 3 列的矩阵,而需要 4 列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 2010-10-19
      • 2014-06-30
      • 2011-11-16
      • 2011-05-08
      • 2010-11-23
      相关资源
      最近更新 更多