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

Time:08-08

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.

CodePudding user response:

x <- c(1,2,3)

for (i in 1:5) {
    x = myfunc(x);
}

outputs [1] 32 64 96, as does myfunc(myfunc(myfunc(myfunc(myfunc(x))))).

Just keep reassigning in a loop?

CodePudding user response:

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

CodePudding user response:

You can use:

x <- c(1,2,3)
myfunc <- function(x){
  res <- 2*x
  x <<- res
  return(res)
}

The double assign operator makes sure that your initial x gets overwritten in each function call.

Here‘s the result for 5 runs:

replicate(5, myfunc(x))

     [,1] [,2] [,3] [,4] [,5]
[1,]    2    4    8   16   32
[2,]    4    8   16   32   64
[3,]    6   12   24   48   96

CodePudding user response:

Here's a one liner. Recall allows for recursive calling based on a condition. Here I assume whatever happens in the expression in my_fun is vectorized, as * is. If it is not, wrap the function in Vectorize.

f <- function(n, rep) if(rep) Recall(n * 2, rep - 1) else n
f(1:3, 5)
[1] 32 64 96
  •  Tags:  
  • r
  • Related