这是一个两部分的问题。我想根据不同的插槽值设置原型(prototype) s4 对象的值,或者我想将其作为一种方法来实现。
我有一个我正在尝试创建的对象。它有一些插槽。我想根据从另一个插槽输入的值设置一个插槽值。这是我想做的简化版本。
IE。,
setClass("Person",
representation(name = "character", age = "numeric", doubleAge = "numeric"),
prototype(name = "Bob", age = 5, doubleAge = 10) )
现在我想创建一个对象,但根据年龄槽设置自己的 doubleAge 值。
p1 <- new("Person", name = "Alice", age = 6)
我懂了
An object of class "Person"
Slot "name":
[1] "Alice"
Slot "age":
[1] 6
Slot "doubleAge":
[1] 10
但我想看到doubleAge是12。在原型(prototype)中,我不知道如何更改
doubleAge = 10
类似于 doubleAge = 2*age
因此,作为解决方案,我尝试制作设置功能
init
它在创建后设置值。这是第 2 部分的问题。setGeneric("init", "Person", function(object) {
standardGeneric("init")
}
setMethod("init","Person", function(object) {
object@doubleAge <- object@age*2
object
}
如果我打印
object@doubleAge
在方法中它返回 12 但似乎范围结束了,因为它返回时为 10目前有效的方法非常相似,但不正确。
setGeneric("init<-", "Person", function(object) {
standardGeneric("init<-")
}
setMethod("init<-","Person", function(object) {
object@doubleAge <- object@age*2
object
}
但是我必须像
init(p1) <- NULL
一样打电话这看起来很奇怪。我知道这个例子看起来微不足道,但它只是一个更复杂的现实世界问题的简单例子。
最佳答案
似乎覆盖初始化方法对我有用。例如
setClass("Person",
representation(name = "character", age = "numeric", doubleAge = "numeric"),
prototype(name = "Bob", age = 5, doubleAge = 10) )
setMethod("initialize", "Person", function(.Object, ...) {
.Object <- callNextMethod()
.Object@doubleAge <- .Object@age*2
.Object
})
(p1 <- new("Person", name = "Alice", age = 6))
# An object of class "Person"
# Slot "name":
# [1] "Alice"
# Slot "age":
# [1] 6
# Slot "doubleAge":
# [1] 12
callNextMethod()
运行“默认”初始化程序来设置我们没有搞砸的所有值。然后我们只需更改我们想要的值并返回更新的对象。
关于r - 如何使用方法在 S4 对象 r 中设置值(无需输入值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54795434/