S4 方法子集通用替换环境

S4 method subsetting generic replace environment

我在文档中迷路了,真的不知道该做什么。我认为解决方案是使用环境,但即使我觉得它没有那么复杂,我也想不通。

这是一个使用两个 类:

的简单示例
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){
        theObject@age <- value;
        return(theObject);
    });

setReplaceMethod(

    f = "setid",

    signature = "Person",

    definition = function(theObject, value){
        theObject@id <- value;
        return(theObject);
    });

setMethod(

    f = "[[",

    signature = c("PersonList", "ANY", "ANY"),

    definition = function(x, i, j, ...){

        return(x@datasetList[[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]]))
    });

通过文档,这变得非常复杂。任何人都可以提示我如何执行此操作吗?

非常感谢。

您只需为您的 PersonList class 定义 [[<-:

setMethod(
    f = "[[<-",
    signature = c("PersonList"),
    definition=function(x,i,j,value) {
        x@datasetList[[i]] <- value
        return(x)
    })

那么你的代码应该可以工作了。不过,您可以添加一些代码来检查完整性。喜欢 inherits(value, "Person")missing(j).