0
我迷失在文档中,真的失去了做什么的轨道。我认为解决方案是使用环境,但即使我觉得它不那么复杂,我也无法弄清楚。S4方法子集化通用替换环境
下面是使用两个类一个简单的例子:
Person <- setClass(
Class = "Person",
slots = c(name = "character",
id = "numeric",
age = "numeric"));
PersonList <- setClass(
Class = "PersonList",
slots = c(datasetList = "list"));
这里是对象的创建:
mary <- new("Person", name = "Mary", id = 1, age = 35);
peter <- new("Person", name = "Peter", id = 2, age = 39);
john <- new("Person", name = "John", id = 3, age = 25);
employees <- new("PersonList", datasetList = list(mary, peter, john));
我再定义两个方法来设置年龄和ID和方法对于子设置PersonList:
setGeneric(name = "setAge<-", def = function(theObject, value){standardGeneric("setAge<-");});
setGeneric(name = "setid<-", def = function(theObject, value){standardGeneric("setid<-");});
setReplaceMethod(
f = "setAge",
signature = "Person",
definition = function(theObject, value){
[email protected] <- value;
return(theObject);
});
setReplaceMethod(
f = "setid",
signature = "Person",
definition = function(theObject, value){
[email protected] <- value;
return(theObject);
});
setMethod(
f = "[[",
signature = c("PersonList", "ANY", "ANY"),
definition = function(x, i, j, ...){
return([email protected][[i]]);
});
现在,这里的问题是:
> setAge(employees[[1]]) <-56
Error in `[[<-`(`*tmp*`, 1, value = new("Person",
name = "Mary", id = 1, :
[[<- defined for objects of type "S4" only for subclasses of environment
如果我理解正确的话我必须使用环境中得到的东西,如:
setMethod(
f = "[[<-",
signature = c("PersonList", "ANY", "ANY"),
definition = function(x, i, j, ...){
if environment is setid return(setId(x[[i]]))
if environment is setAge return(setAge(x[[i]]))
});
通过文档,这是越来越复杂,真正走出去。任何人都可以给我一个关于如何做到这一点的提示吗?
非常感谢。
谢谢!!这是棘手的理解,但它的工作。 – nicoluca
是的,它是棘手的,但如果你想一想,命令行'setAge(employees [[1]])<-56'应该如何知道它应该写入'employees @ datsetList'?,它开始有意义。如果对你有帮助,随时欢迎/接受答案。 –