[R] Error using return() function inside for loop and if statement

2012-04-10 Thread C W
Dear all, I get an error using the return function. The following is a simpler version. for (j in 1:10) { samples = 5*j return(samples) } Error: no function to return from, jumping to top level Similar warning happens with if statement. Why do I get an error? print() works fine. I

Re: [R] Error using return() function inside for loop and if statement

2012-04-10 Thread R. Michael Weylandt
The error message should make it pretty clear -- you aren't inside a function so you can't return() a value which is, by definition, what functions (and only functions) do.** Not sure there's a great reference for this though beyond the error message Incidentally, what are you trying to do

Re: [R] Error using return() function inside for loop and if statement

2012-04-10 Thread C W
Thanks. So, I want the function to return results from the if statement. bob - function(var1, func) { #func: a simple function num1 - var1 num2 - func(var1) if(ruinf(1)num1) { return(num1) }else{ return(num2) } } And then, run 20 iterations of the function.

Re: [R] Error using return() function inside for loop and if statement

2012-04-10 Thread R. Michael Weylandt
You don't need to return() from the for loop -- just put your outputs in a variable: set.seed(1) # For reproducibility x - numeric(20) for(i in 1:20) x[i] - bob(0.5, sqrt) or (more elegant but basically the same thing) set.seed(1) x1 - replicate(20, bob(0.5, sqrt)) # Same calculation done 20x