I am working on a complicated project, and each time I need to run my function using the result of the previous run of the function. To make my point clearer, suppose that I have a vector x, and a function myfunc. Then, I need to run myfunc using the vector x. Then, I take the output of my function and plug them again as an argument of the same function. I need to repeat this automatically several times.
For example,
x <- c(1,2,3)
myfunc <- function(x){
res <- 2*x
return(res)
}
Then,
x <- myfunc(x)
> x
[1] 2 4 6
x <- myfunc(x)
> x
[1] 4 8 12
How can I do this automatically (repeat for, say, 5 times)? In the end, I need the result of the final run only. For example, the result of the fifth run.
>Solution :
A good way to do so would be to include an argument repeats in your function itself.
myfunc <- function(x, repeats=1){
res <- x
for(i in 1:repeats) {
res <- 2*res
}
return(res)
}
> myfunc(x, 5)
[1] 32 64 96