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

Appending results to a list in a recursive loop in R

I am working on code that solves a differential equation numerically. The dydx_solve function is recursive and the results are supposed to be appended to a list called results that look like

[1] -0.1
[2] 0.1
[3] -0.001
...
[100] -1e-101

instead I’m getting solutions that’s just

[[1]]
[1] -0.1

If I add print(y_n) in the if statement then I get all the values I need but not in a list. Where am I going wrong and how can I add all y_n values to a single results list?

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

dx=0
y1=1
x1=1



slope=function(y){
  dydx<- -y
  return(dydx)
}




dydx_solve=function(x,y){
  
  results<-list()
  
  stepper<-0.1
  
  if(x<10){
    x<-x+stepper
    y_n<-slope(y) *(x-(x-stepper))
    results<-append(results, list(y_n))
    dydx_solve(x,y_n)
    print(results)
    
  }else{
    #pass
  }
  
  return(results)
  
}


print(dydx_solve(dx, y1))
print(results)

>Solution :

Try:

dydx_solve <- function(x,y, results=list()){
    
  stepper <- 0.1
  
  if (x < 10) {
    x <- x + stepper
    y_n <- slope(y) * (x-(x-stepper))
    results <- append(results, list(y_n))
    dydx_solve(x, y_n, results)
  } else {
    #pass
    return(results)
  }  
}

# only show the last 3 elements
tail(dydx_solve(dx, y1), 3)
# [[1]]
# [1] -1e-99
# 
# [[2]]
# [1] 1e-100
# 
# [[3]]
# [1] -1e-101

Rather than save your results, each time you call dydx_solve() your first line creates an empty list. In your call, you need to pass your updated list to your results argument and not overwrite it with an empty list with results<-list().

Also you need to move your return() into your else condition.

Note: this runs quickly for this task but growing a list with append() can slow down your code if you have a lot of iterations.

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