如何在S4class中初始化新对象?
How to initialize the new object in S4 class?
我有如下数据:
data = data.frame( id = rbinom(1000, 10, .75),
visit = sample(1:3, 1000, replace = TRUE),
room = sample(letters[1:5], 1000, replace = TRUE),
value = rnorm(1000, 50, 10),
timepoint = abs(rnorm(1000))
)
head(data)
id visit room value timepoint
1 8 3 a 62.53394 1.64681140
2 9 1 c 53.67313 1.04093204
3 6 1 c 64.96674 0.40599449
4 8 2 d 41.04145 0.09911475
5 7 2 b 63.86938 1.01732424
6 7 3 c 42.03524 2.04128413
我已经定义了一个 S4 class 来读取这个数据作为 longitudinalData
。 class 如下所示。
setClass("longitudinalData",
slots = list(id = "integer",
visit = "integer",
room = "character",
value = "numeric",
timepoint = 'numeric'))
为了在此 class 中启动一个新对象,我定义了以下函数。
make_LD = function(x){
new("longitudinalData",
id = x$id,
visit = x$visit,
room = x$room,
value = x$value,
timepoint = x$timepoint
)
}
当我尝试通过 make_LD(data)
添加新对象时,出现以下错误。
> make_LD(data)
Error in initialize(value, ...) :
no slot of name "refMethods" for this object of class "classRepresentation"
这个错误是什么意思?
如何摆脱这个?
避免此类问题的最简单方法是保存 setClass
中的值,returns 一个方便的构造函数供您使用。
setClass("longitudinalData",
slots = list(id = "integer",
visit = "integer",
room = "character",
value = "numeric",
timepoint = 'numeric')) -> longitudinalData
make_LD = function(x){
longitudinalData(
id = x$id,
visit = x$visit,
room = x$room,
value = x$value,
timepoint = x$timepoint
)
}
给构造函数取与 class 相同的名称是正常的,但您不必这样做。
我有如下数据:
data = data.frame( id = rbinom(1000, 10, .75),
visit = sample(1:3, 1000, replace = TRUE),
room = sample(letters[1:5], 1000, replace = TRUE),
value = rnorm(1000, 50, 10),
timepoint = abs(rnorm(1000))
)
head(data)
id visit room value timepoint
1 8 3 a 62.53394 1.64681140
2 9 1 c 53.67313 1.04093204
3 6 1 c 64.96674 0.40599449
4 8 2 d 41.04145 0.09911475
5 7 2 b 63.86938 1.01732424
6 7 3 c 42.03524 2.04128413
我已经定义了一个 S4 class 来读取这个数据作为 longitudinalData
。 class 如下所示。
setClass("longitudinalData",
slots = list(id = "integer",
visit = "integer",
room = "character",
value = "numeric",
timepoint = 'numeric'))
为了在此 class 中启动一个新对象,我定义了以下函数。
make_LD = function(x){
new("longitudinalData",
id = x$id,
visit = x$visit,
room = x$room,
value = x$value,
timepoint = x$timepoint
)
}
当我尝试通过 make_LD(data)
添加新对象时,出现以下错误。
> make_LD(data)
Error in initialize(value, ...) :
no slot of name "refMethods" for this object of class "classRepresentation"
这个错误是什么意思?
如何摆脱这个?
避免此类问题的最简单方法是保存 setClass
中的值,returns 一个方便的构造函数供您使用。
setClass("longitudinalData",
slots = list(id = "integer",
visit = "integer",
room = "character",
value = "numeric",
timepoint = 'numeric')) -> longitudinalData
make_LD = function(x){
longitudinalData(
id = x$id,
visit = x$visit,
room = x$room,
value = x$value,
timepoint = x$timepoint
)
}
给构造函数取与 class 相同的名称是正常的,但您不必这样做。