gpt4 book ai didi

r - 如果未提供变量,为什么用 data.table 插槽初始化 R S4 类不起作用

转载 作者:行者123 更新时间:2023-12-05 07:39:58 25 4
gpt4 key购买 nike

我正在尝试创建一个包含 data.table 的对象,如果在 new 语句中没有提供任何内容,我希望将其初始化为一个空的 data.table。但是,如果我将其遗漏,则会收到一条错误消息。

我尝试使用 data.frame 代替,这很好,但我想了解下面最后一个新声明中出了什么问题,因为前 2 个新声明是好的?

library(data.table)

setClass("TmpClass", slots = c(v1 = "character", v2 = "data.frame"))
new("TmpClass", v1 = "I work")
# An object of class "TmpClass"
# Slot "v1":
# [1] "I work"
#
# Slot "v2":
# data frame with 0 columns and 0 rows

setClass("JunkClass", slots = c(v1 = "character", v2 = "data.table"))
new("JunkClass", v1 = "I work as well", v2 = data.table(a = 1, b = 2))
# An object of class "JunkClass"
# Slot "v1":
# [1] "I work as well"
#
# Slot "v2":
# a b
# 1: 1 2

new("JunkClass", v1 = "hmm, i get an error")
# Error in validObject(.Object) :
# invalid class “JunkClass” object: invalid object for slot "v2" in class
# "JunkClass": got class "list", should be or extend class "data.table"

最佳答案

我认为这里一个好的解决方案是正式承认 @v2 插槽可以是 NULL

library(data.table)
setClassUnion("nullOrDatatable", c("NULL", "data.table"))
setClass("JunkClass", slots = c(v1 = "character", v2 = "nullOrDatatable"))
new("JunkClass", v1 = "No more error!")
# An object of class "JunkClass"
# Slot "v1":
# [1] "No more error!"
#
# Slot "v2":
# NULL

关于r - 如果未提供变量,为什么用 data.table 插槽初始化 R S4 类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607932/

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