问题

当使用r OOP系统在s4中编程时,当必须使用setReplaceMethod时是我看不到将setMethod添加到函数名称时与<-有什么区别。 setMethod("$<-")setReplaceMethod("$")是否相等?

文献资料

  • 我在文档中找不到?setReplaceMethod??setReplaceMethod的任何内容。除了用法外,没有其他任何东西。
  • 在StackOverflow中,有several questions about setReplaceMethod但没有帮助。当我看到似乎是not possible to use roxygen2 来记录用setReplaceMethod创建的方法
  • 时,我开始搜索此问题的答案
    searching in r-project.org我没有找到任何东西ojit_a
    可繁殖的例子
    library(methods)
    
    # Create a class
    setClass("TestClass", slots = list("slot_one" = "character"))
    
    # Test with setMethod -----------------------
    setMethod(f = "$<-", signature = "TestClass",
      definition = function(x, name, value) {
        if (name == "slot_one") x@slot_one <- as.character(value)
        else stop("There is no slot called",name)
        return(x)
      }
    )
    # [1] "$<-"
    
    test1 <- new("TestClass")
    test1$slot_one <- 1
    test1
    
    # An object of class "TestClass"
    # Slot "slot_one":
    #   [1] "1"
    
    # Use setReplaceMethod instead -----------------------
    setReplaceMethod(f = "$", signature = "TestClass",
      definition = function(x, name, value) {
        if (name == "slot_one") x@slot_one <- as.character(value)
        else stop("There is no slot called",name)
        return(x)
      }
    )
    
    # An object of class "TestClass"
    # Slot "slot_one":
    #   [1] "1"
    test2 <- new("TestClass")
    test2$slot_one <- 1
    test2
    # [1] "$<-"
    
    # See if identical
    identical(test1, test2)
    # [1] TRUE
    

    实际结论
    setReplaceMethod似乎仅允许在创建set方法时避免<-。因为roxygen2不能记录使用它生成的方法,所以暂时最好使用setMethod。我有权利吗?

    最佳答案

    这是setReplaceMethod的定义

    > setReplaceMethod
    function (f, ..., where = topenv(parent.frame()))
    setMethod(paste0(f, "<-"), ..., where = where)
    <bytecode: 0x435e9d0>
    <environment: namespace:methods>
    

    它在名称上粘贴了“setMethod("$<-")。 setReplaceMethod传达了更多的语义含义。

    关于r - setMethod ("$<-"和setReplaceMethod ("$"有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24253048/

    10-12 21:16