Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a result of a function the arguments of the same function atumatically in R

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading