[英]How to write an R function which assigns to the object of the calling environment?
我有一个包含几个矩阵的特定类的对象,并且我想构建一个函数,该函数可以访问并可能修改此矩阵的子集。 例如:
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
的功能。 为此,我需要在调用环境中找到原始对象,但是我不确定该怎么做。
普遍认为这是一个警告,您可以使用以下方法:
在目标环境中,为环境设置一个变量,然后将该变量作为参数传递给您的函数,您可以在assign
, get
等中使用该函数
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.