2

I have a function that takes a numeric value, and produces a numeric value. My code is as follows:

p<-function(a){
  sp(bp(a))
}

The sp and bp functions take a numeric entry, and produce a numeric outcome (sp and bp follow different operations). I want to run this function many times. The following code:

sp(bp(sp(bp(sp(bp(a)))))) 

has the effect I want, but obviously this isn't a practical approach for high numbers of iterations. How can I repeatedly feed the output of p back in to p as the input?

5
  • maybe with a for loop? for(i in 1:n){x <- f(x)} Commented Sep 11, 2020 at 18:57
  • 1
    Can you share your function and tell which argument should be passed back to which input? Commented Sep 11, 2020 at 18:57
  • I've edited the question to provide more details on my specific problem. Commented Sep 11, 2020 at 19:21
  • What about recursive function like in n factorial? Commented Sep 11, 2020 at 19:35
  • Agree with @Liman. But what's your base case? When do you want to stop calling the fucntion on its outpu. Commented Sep 11, 2020 at 19:45

1 Answer 1

1

EDIT: After clarification

So, if it is some known (limited) number of times you would like to apply p in succession, this would be one way (I have assumed some simple functions for sp and bp for illustration):

sp <- function(x) return(x+1)
bp <- function(x) return(2*x)
p <- function(x) return(sp(bp(x)))

# Applying p 3 times in succession:
p_old <- 1
for (i in 1:3){
  p_new =  p(p_old)
  p_old = p_new
}

p_new
#> [1] 15
# Which is the same as
p(p(p(1)))
#> [1] 15

Created on 2020-09-11 by the reprex package (v0.3.0)

I am not quite sure what use case you have in mind (because that can easily lead to an infinite "loop", but here is one (admittedly contrived) example of a function which sums some numbers regardless in how many lists they can be nested which is using a call of the same function in the function definition itself:

sum_of_c_or_list <- function(x){
  
  if (!is.list(x)) return(sum(x))
  else {
    x = unlist(x)
    x = sum_of_c_or_list(x)
    return(x)
  }
}
sum_of_c_or_list(1:3)
#> [1] 6
sum_of_c_or_list(list(1,2,3))
#> [1] 6
sum_of_c_or_list(list(list(1,2,3)))
#> [1] 6

Created on 2020-09-11 by the reprex package (v0.3.0)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - I don't think this approach can be used for my specific problem - I've updated the description to provide more details.
Just to add here: stackoverflow.com/questions/53026344/… can also be of interest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.