gpt4 book ai didi

r - 将 S4 对象存储在矩阵中

转载 作者:行者123 更新时间:2023-12-02 01:49:02 25 4
gpt4 key购买 nike

我正在尝试将一个简单的自定义 S4 对象放入容器中,例如 data.framematrix数据表。当尝试将我的 Course 类实例分配到 matrix 中时

slots <- matrix(NA, ncol = 5, nrow = 5)
slots[1,1] <- new(Class="Course", ATTRIBUTES GO HERE...)

我收到以下错误:

number of items to replace is not a multiple of replacement length

尽管调用 length(MYOBJECTINSTANCE) 返回 1。

那是我的课

setClass(
Class="Course",
representation=representation(
tutor = "character"
#other attributes...
)
)

我还尝试实现一个总是返回 true 的虚拟 validate 方法,但没有效果。

setValidity("Course", function(object) {
return(TRUE)
})

所以现在我的问题是:
是否有一种简单的方法可以将 S4 对象添加到 matrix 或等效容器中?

最佳答案

您可以创建一个以 S4 对象作为元素的矩阵,方法是先将项目放入列表中。

slots <- list(
new(Class="Course"),
new(Class="Course"),
new(Class="Course"),
new(Class="Course"))

然后只需相应地设置dim属性即可获得一个矩阵:

dim(slots) <- c(2,2)

例子:

slots # don't bother
## [,1] [,2]
## [1,] ? ?
## [2,] ? ?
slots[[1,1]] # element access
## An object of class "Course"
## Slot "tutor":
## character(0)

关于r - 将 S4 对象存储在矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23898644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com