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

如何编写分配给调用环境对象的R函数?,r,function,global-variables,subset,assignment-operator,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,"ty

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

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有一点需要注意,这通常是不赞成的,您可以使用以下方法:

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

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

好的,我自己找到了一个解决方案


foo如果您只是在更改属性,那么内置的
attr将非常感谢,但问题是原始对象的名称,即“varname”可以是任意的。@Hemmo,这是个什么问题?在
assign
中使用一个不带引号的变量如果我在调用环境中有一个名为myvar的对象,并且我运行函数myfunc(var,en),那么函数myfunc不知道我需要为名为myvar的变量赋值。但这并不重要,我找到了另一个解决方案,我将很快发布。
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<-
en <- environment()
myfunc <- function(..., en=en) {
  . etc .
  assign("varname", envir=en)
}
 setattr(x,name,value)
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