我有一个包含多个矩阵的某个类的对象,我想构建一个函数来访问并可能修改此类矩阵的子集。例如:
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
函数将更改复制到调用环境中的对象。为此,我需要在调用环境中找到原始对象,但我不知道该怎么做。