How to write an R function which assigns to the object of the calling environment? -
i have objects of class contain several matrices, , build function access , possibly modifies subset of such matrix. example:
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")
now access , modify elements this:
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)
but instead of above, construct following type of function:
modify<-function(object,element,types){ # check object proper class, # , element , types found in object # returns local copy of corresponding subset: object[[element]][attr(object,"types")%in%types,attr(object,"types")%in%types] }
for accessing above function ok, if want modify original object? doesn't work:
modify(foo,"x",c("c","b"))<-matrix(5,3,3) error in modify(foo, "x", c("c", "b")) <- matrix(5, 3, 3) : not find function "modify<-
is possible work somehow? if not, 1 option think of adding argument replace.with
function modify
, making assignment first local copy , copying change object in calling environment using assign
function. need find original object in calling environment, i'm not sure how that.
with caveat frowned upon, can use following:
from target environment, set variable environment , pass argument function can use in assign
, get
etc
en <- environment() myfunc <- function(..., en=en) { . etc . assign("varname", envir=en) }
note if changing attributes, setattr
function of data.table package implements quote nicely:
setattr(x,name,value)
Comments
Post a Comment