2

Take a basic function

fun<-function(){
x<-c(1,2,3,4,5)
y<-c(1,2,3,4,5)

t<-x+y
return(t)

}

After I have run the function, is there a way I can access any of the variables created within the function. Either by specifying the variable- something like this:

fun$y

or

fun$t

or is there some way of asking R to save the variable within the function for use during my current R session (I'm not looking to save it permanently). AKA something along the lines of:

fun<-function(){
x<-c(1,2,3,4,5)
y<-c(1,2,3,4,5)

t<-x+y
Y<-save y for latter use
T<-save T for latter use
return(t)

}

Thanks!

Vinterwoo
  • 3,843
  • 6
  • 36
  • 55

2 Answers2

5

You can't use a variable outside of its scope.

What you can do is use a list to return multiple values from your function.

Here's a good example.

Community
  • 1
  • 1
Benito Bertoli
  • 25,285
  • 12
  • 54
  • 61
  • Perhaps I'm missing something important. But if I were to follow the info in your link and add two lines to the above code "newList<-list("YY"=y,"XX"=x)" & "return(newList)"- after I execute the function- if I type in newList$XX I get the message "Error:object 'newList' not found. – Vinterwoo Jun 15 '12 at 23:39
  • @VincentMoriarty Once again, functions don't (in general) have side effects. If your function `return`s something, you have to _assign_ the output of your function to something. i.e. `result <- fun()`. – joran Jun 16 '12 at 00:09
  • You're still trying to access the function's local variable. Use result<-fun() then result$XX. – Benito Bertoli Jun 16 '12 at 00:13
  • That's the ticket! Thanks guys – Vinterwoo Jun 16 '12 at 00:23
4

Yes and no.

Yes, it is technically possible to make assignments to variables outside the scope of your function, so that they are accessible elsewhere. Typically this is done using either <<-, which assigns in the global environment if the variable being assigned can't be found, or calling assign and specifying an environment directly.

But...

No, you should probably not be doing this. R is a functional language, which means that it is intended to be used such that its functions do not create side-effects. If you violate this principle too much, you will inevitably run afoul of serious problems that will be difficult, if not impossible to debug.

If you create variables within a function that you will need later, it is considered best practice to return them all in a list, as Benito describes.

joran
  • 169,992
  • 32
  • 429
  • 468