如何编写分配给调用环境的对象的R函数



我有一个特定类的对象,它包含几个矩阵,我想构建一个函数,访问并可能修改这些矩阵的子集。例如:

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<-

有可能以某种方式完成那项工作吗?如果没有,我可以考虑的一个选项是向函数modify添加参数replace.with,然后首先向本地副本赋值,然后使用assign函数将更改复制到调用环境中的对象。为此,我需要在调用环境中找到原始对象,但我不确定如何做到这一点。

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

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

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

注意,如果您只是简单地更改属性,data.table包的setattr函数已经很好地实现了这句话:

 setattr(x,name,value)

好的,我自己在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

相关内容

  • 没有找到相关文章

最新更新