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

时间:2013-08-07 11:35:25

标签: r function global-variables subset assignment-operator

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

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,然后首先将赋值赋给本地副本,然后使用{{1将更改复制到调用环境中的对象功能。为此,我需要在调用环境中找到原始对象,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

有一点需要注意,你可以使用以下内容:

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

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

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

 setattr(x,name,value)

答案 1 :(得分:0)

好的,我在R-help by Brian Ripley:

的旧帖子的帮助下找到了解决方案
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