你可能想看看使用 R::setClass
本质上,这允许您创建一个类定义并返回一个生成器函数以从该类创建对象。就个人而言,我发现它在您描述的上下文中非常有用。要取消引用结构组件,您可以使用@,使用下面的示例CStructure@powerLevel 将返回5
作为替代方案,可以考虑使用数据框,但是,数据框方法不会创建独立的类模板。它还要求所有条目的长度相同。数据框对称,您的数据可能不是。
请参阅示例错误参考:数据帧必须是对称的在下面使用setClass 的示例详细说明。也就是说,两者都是选项。
希望这个例子对你有用。
示例
setClass(
"CStruct",
slots = list(
powerLevel = "numeric",
size = "numeric"
)
)
CStructure <- new("CStruct", powerLevel =5, size=10)
CStructure
str(CStructure)
CStructure@powerLevel
CStructure@size
输出:
> setClass(
+ "CStruct",
+ slots = list(
+ powerLevel = "numeric",
+ size = "numeric"
+ )
+ )
>
> CStructure <- new("CStruct", powerLevel =5, size=10)
> CStructure
An object of class "CStruct"
Slot "powerLevel":
[1] 5
Slot "size":
[1] 10
> str(CStructure)
Formal class 'CStruct' [package ".GlobalEnv"] with 2 slots
..@ powerLevel: num 5
..@ size : num 10
> CStructure@powerLevel
[1] 5
> CStructure@size
[1] 10
>
数据框必须是对称的
> n = c(2, 3, 5)
> s = c("aa", "bb")
> b = c(TRUE, FALSE, TRUE)
> df = data.frame(n, s, b)
Error in data.frame(n, s, b) :
arguments imply differing number of rows: 3, 2
CStruct 替代方案
setClass(
"CStruct2",
slots = list(
n = "numeric",
s = "character",
b = "logical"
)
)
CStructure2 <- new("CStruct2", n = c(2, 3, 5),
s = c("aa", "bb"),
b = c(TRUE, FALSE, TRUE) )
str(CStructure2)
CStructure2@n
CStructure2@s
CStructure2@b
输出:
> setClass(
+ "CStruct2",
+ slots = list(
+ n = "numeric",
+ s = "character",
+ b = "logical"
+ )
+ )
>
> CStructure2 <- new("CStruct2", n = c(2, 3, 5),
+ s = c("aa", "bb"),
+ b = c(TRUE, FALSE, TRUE) )
> str(CStructure2)
Formal class 'CStruct2' [package ".GlobalEnv"] with 3 slots
..@ n: num [1:3] 2 3 5
..@ s: chr [1:2] "aa" "bb"
..@ b: logi [1:3] TRUE FALSE TRUE
> CStructure2@n
[1] 2 3 5
> CStructure2@s
[1] "aa" "bb"
> CStructure2@b
[1] TRUE FALSE TRUE