【发布时间】:2019-07-11 12:30:13
【问题描述】:
我在 R 中创建了两个类:
library(methods)
Foo <- setClass(
# Set the name for the class
"Foo",
# Define the slots
slots = c(
# THIS IS PROBABLY WRONG
bar = "S4"
),
)
还有
Bar <- setClass(
# Set the name for the class
"Bar",
# Define the slots
slots = c(
a = "character"
),
# Set the default values for the slots. (optional)
prototype=list(
a = "qwerty"
),
)
我想说一些类似于Foo.bar <- Bar() 的内容。我认为应该这样做:
# create a method to assign the value of a coordinate
setGeneric(name="addBar",
def=function(theObject)
{
standardGeneric("addBar")
}
)
setMethod(f="addBar",
signature="Foo",
definition=function(theObject)
{
theObject@bar<- Bar
}
)
然后我使用:
if (!interactive()) {
result <- tryCatch({
foo <- Foo()
foo <- addBar(Foo)
}
,
warning = function(war) {
print('A warning occurred')
print(war)
},
error = function(err){
print('An error occurred')
print(err)
}
)
print(result)
}
但是,如果我运行它,我会受到欢迎:
“Bar”类对象的赋值对于“Foo”类对象中的@'bar'无效; is(value, "S4") 不是 TRUE>
但是,当我打印 Bar 的类型时,我得到 S4。我尝试了多种不同的类型,但我的想法很新鲜。
如何将类对象分配给变量?
【问题讨论】: