Does using package generics require the package to be in Depends or Imports?

后端 未结 1 1149
花落未央
花落未央 2021-01-22 14:07

First of all, I have read around this topic a lot. I have studied the conversations here, here, here and here. The problem is, however, I still think one particular topic isn\'t

1条回答
  •  情歌与酒
    2021-01-22 15:01

    I'm not a complete expert on this, but here is something that works:

    #' @importFrom ggplot2 autoplot
    #' @export autoplot
    
    autoplot <- autoplot
    
    #' @export "autoplot.foo"
    
    autoplot.foo <- function(obj, ...) {
      cat("bar\n")
    }
    

    Unfortunately we need to explicitly export the method because for some reason S3 dispatch from a package namespace (in this case ggplot2) doesn't find the method registered from a package it doesn't import from. This kind of makes sense except that it works for base generics so there is a subtlety of the S3 registration mechanism that I'm not privy to.

    Re whether to use :: within your package or not, it's up for debate. You don't have to if you use @import or @importFrom, but some (including Hadley) suggest you should for clarity. I personally recommend against it because the R profiler doesn't resolve function names of the style package::method, which makes it harder to optimize code (there are workarounds that can meet both objectives).

    Note you should absolutely use @import and not rely solely on :: (you will also have to update the DESCRIPTION file). Failing to do so will prevent R from being aware of the dependency. I'm pretty sure R CMD check yells about this.

    0 讨论(0)
提交回复
热议问题