nabble.30.miller_2555 at spamgourmet.com
2009-Jul-21 00:07 UTC
[R] Accessing list object from within a function as a list element
Hi - I have a list (call it 'mylist') with the following elements: (i) a function (call it 'myfunc' and expressed as 'mylist$myfunc') and (ii) a variable (call it 'myvar' and expressed as 'mylist$myvar'). Since I use mylist as a pseudo-class (I assign mylist to multiple different R objects), I would like to access the mylist R object from within the 'myfunc' function to use 'myvar.' Here is a simple example: mylist <- list(); mylist$myvar <- "~/file.out"; mylist$myfunc <- function (mymsg="hello world") { cat(mymsg,mylist$myvar); }; If I perform the following: myclassobj_1 <- myclassobj_2 <- myclassobj_3 <- mylist; myclassobj_1 <- "~/file_1.out"; myclassobj_2 <- "~/file_2.out"; myclassobj_3 <- "~/file_3.out"; I cannot use myclassobj_1$myfunc() as it will place "hello world" into "~/file.out" instead of "~/file_1.out." Unless I want to make the myclassobj_? lists an argument to the 'myfunc' function, I need an object reference to the appropriate 'mylist.' For instance: mylist$myfunc <- function (mymsg="hello world") { objref <- <function returning container list>; cat(mymsg,objref$myvar); }; I had some success with the sys.call() function, though the implementation is sloppy and inconsistent as it relies on the environment frame in which the call is made as opposed to an attribute of the 'myfunc' function. Any suggestions as to this specific issue or preferred implementation of user-defined classes in R? Thanks!