0

我有一个包含多个矩阵的某个类的对象,我想构建一个函数来访问并可能修改此类矩阵的子集。例如:

foo<-list(x=diag(1:4),y=matrix(1:8,2,4))
class(foo)<-"bar"
attr(foo,"m")<-4
attr(foo,"p")<-2
rownames(foo$x)<-colnames(foo$x)<-colnames(foo$y)<-c("a.1","b.1","b.2","c.1")
attr(foo,"types")<-c("a","b","b","c")

现在我可以像这样访问和修改某些元素:

foo$x[attr(foo,"types")%in%c("c","b"),attr(foo,"types")%in%c("c","b")]    
foo$x[attr(foo,"types")%in%c("c","b"),attr(foo,"types")%in%c("c","b")]<-matrix(5,3,3)

但不是上面的,我想构造以下类型的函数:

modify<-function(object,element,types){
  # check that the object is proper class, 
  # and the element and the types are found in the object

  # this returns to the local copy of the corresponding subset:
   object[[element]][attr(object,"types")%in%types,attr(object,"types")%in%types]     
}

访问上述功能是可以的,但是如果我想修改原始对象怎么办?显然这不起作用:

modify(foo,"x",c("c","b"))<-matrix(5,3,3)
Error in modify(foo, "x", c("c", "b")) <- matrix(5, 3, 3) : 
  could not find function "modify<-

有可能以某种方式完成这项工作吗?如果没有,我能想到的一个选择是向replace.with函数添加参数modify,然后首先将分配分配给本地副本,然后使用assign函数将更改复制到调用环境中的对象。为此,我需要在调用环境中找到原始对象,但我不知道该怎么做。

4

2 回答 2

1

需要注意的是,这通常是不受欢迎的,您可以使用以下内容:

从目标环境中,为环境设置一个变量,然后将其作为参数传递给您可以在等中使用assignget函数

en <- environment()
myfunc <- function(..., en=en) {
  . etc .
  assign("varname", envir=en)
}

请注意,如果您只是更改属性,setattr则 data.table 包的功能已经很好地实现了这个引用:

 setattr(x,name,value)
于 2013-08-07T11:51:50.213 回答
0

好的,我在Brian Ripley的 R-help 旧帖子的帮助下自己找到了一个解决方案:

foo<-list(x=diag(1:4),y=matrix(1:8,2,4))
class(foo)<-"bar"
attr(foo,"m")<-4
attr(foo,"p")<-2
rownames(foo$x)<-colnames(foo$x)<-colnames(foo$y)<-c("a.1","b.1","b.2","c.1")
attr(foo,"types")<-c("a","b","b","c")

`modify<-` <- function(x, element, subset,value) UseMethod("modify<-")
`modify<-.bar` <- function(x, element, subset,value) { 

  x[[element]][,attr(foo,"types")%in%subset] <- value
  x }

modify(foo,"x",c("c","b"))<-matrix(5,3,3)
foo$x
    a.1 b.1 b.2 c.1
a.1   1   0   0   0
b.1   0   5   5   5
b.2   0   5   5   5
c.1   0   5   5   5
于 2013-08-09T10:13:29.067 回答