-2

I have some issues to correctly return a variable within a function in R. In the following example, I've created a function for a Leave-One-Out Cross Validation. The problem is that the function doesn't seem to affect the variable 'mse' in any way, it remains as it was initially set up.

I tried to only run the script from the 'for' line and it works well, all the 'mse' values are added to the variable.

LOOCV Screenshot

How come that by using a function, I cannot modify my variable? Is it related to the local/general variables or something?

Thank you.

Jonathan Carroll
  • 3,897
  • 14
  • 34
afkqs
  • 25
  • 1
  • 6
  • You have to assign ie. `mse <- loocv(l)` – akrun Feb 16 '17 at 00:19
  • 4
    I suggest you take a beginners course in `R`. You need to assign the result of a function call to a variable. – Jonathan Carroll Feb 16 '17 at 00:19
  • ... but perhaps a bit clearer to return the mse within the function – user20650 Feb 16 '17 at 00:20
  • 1
    If you need more help with code, please do not post the code as an image. The best method is to make it as easy as possible for us, so providing small and representative data (if needed), the smallest amount of code that shows the problem and works without not-included components, and your expected output. It will be very useful if you spend 45 seconds reading about [minimal, complete, and verifiable examples](http://stackoverflow.com/help/mcve) as well as a popular Q&A on SO about [reproducible questions](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – r2evans Feb 16 '17 at 00:42

1 Answers1

0

In R, functions receive parameters by value. This means that functions do not change their parameters externally. For example, the following code

test <- function(x) {x=5}
a <- 10
test(a)
print(a)

prints:

[1] 10

To return something from a function, use

return(something)
user31264
  • 6,557
  • 3
  • 26
  • 40