使用 data() 作为通用 S4 函数
我正在尝试为 foo
类定义一个新的 data
方法。我的 foo
对象遵循以下结构:
setClass(Class = "foo",
representation = representation(
data = "data.frame",
id = "character",
wl = "numeric"
)
)
我尝试创建的 data
方法实际上是访问 @data
槽的内容:
setMethod("data", "foo",
function(object)
object@data
)
I一直在查看第 7.1 节手册,但它只涉及 S3 类。我还浏览了这篇文章,但没有成功:
setGeneric("data", function(object, ...) standardGeneric('data'))
setMethod("data", "ANY", utils::data)
setMethod("data", "foo",
function(object)
object@data
)
加载包时:
> data(mtcars)
Error in function (classes, fdef, mtable) :
unable to find an inherited method for function "data", for signature "data.frame"
I'm trying to define a new data
method for a foo
class. My foo
objects follow the following structure:
setClass(Class = "foo",
representation = representation(
data = "data.frame",
id = "character",
wl = "numeric"
)
)
The data
method I'm trying to create is actually accessing the contents of the @data
slot:
setMethod("data", "foo",
function(object)
object@data
)
I've been looking at the section 7.1 of the Writing R Extensions manual, but it only deals with S3 classes. I also had a peek at this post, but without success:
setGeneric("data", function(object, ...) standardGeneric('data'))
setMethod("data", "ANY", utils::data)
setMethod("data", "foo",
function(object)
object@data
)
When loading the package:
> data(mtcars)
Error in function (classes, fdef, mtable) :
unable to find an inherited method for function "data", for signature "data.frame"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Pierre,
data
的第一个参数是...
(不是object
!),因此您需要在调度时进行一些特殊考虑。 <代码>? dotMethods 对此进行了讨论。通常(例如
cbind
、rbind
),一个快速的&肮脏的解决方案是对这些函数使用 S3 方法表示法但是,我猜你在这里遇到了麻烦,因为原始数据函数使用了未评估的参数名称,并且错误消息表明它已被评估(确实有道理:R 如何能在调用原始数据函数之前知道参数属于哪个类(如果不求值的话?)。
所以最终使用 data() 以外的其他名称来访问数据槽可能会容易得多。
(你的 wl 插槽让我想到了波长:如果你正在为光谱数据设置一个类,请查看 hyperSpec - 它可能已经提供了您所需要的)。
Pierre,
The first argument of
data
is...
(notobject
!), so you need some special considerations for the dispatch.? dotsMethods
discusses that.Often (e.g.
cbind
,rbind
), a quick & dirty solution is to use S3 method notation for these functionsHowever, I guess you are in trouble here because the original data function uses the unevaluated name of the argument, and the error message suggests that it is evaluated (does make sense: how could R know which class the argument has if it doesn't evaluate?) before the original data function is called.
So in the end it may be much easier to use some other name than data () to access your data slot.
(Your wl slot makes me think of wavelengths: if you are setting up a class for spectroscopic data, have a look at hyperSpec - it may provide already what you need).
对我(我在
S3
世界中)有帮助的是创建从基本utils
包中调用data()
的默认函数:然后调度行为如预期:
What helped me (I am in the
S3
world) was to create default function that callsdata()
from the basicutils
package:Then dispatch behaves as expected: