rfunctionvariablesextract

Get variables that have been created inside a function


I have created a function (which is quite long) that I have saved in a .txt file. It works well (I use source(< >) to access it). My problem is that I have created a few variables in that function ie:

myfun<-function(a,b) {
Var1=....
Var2=Var1 + ..
}

Now I want to get those variables. When I include return() inside the function, its fine: the value comes up on the screen, but when I type Var1 outside the function, I have an error message "the object cannot be found". I am new to R, but I was thinking it might be because "myfun" operates in a different envrionment than the global one, but when I did

environment()
environment: R_GlobalEnv>
environment(myfun1)
environment: R_GlobalEnv>

It seems to me the problem is elsewhere...

Any idea?

Thanks


Solution

  • If you want to do it in a nice way, write a class and than provide a print method. Within this class it is possible to return variables invisible. A nice book which covers such topics is "The Art of R programming".

    An easy fix would be save each variable you need later on an list and than return a list (as Peter pointed out):

    return(list(VAR1=VAR1, .....))