简体   繁体   中英

Recursive function in R of a sequence

I am trying to write a function that takes X and n, and returns element Xn. X is a vector of the first 3 elements of the sequence and n is a positive integer. Xn = Xn-1 + Xn-2 - Xn-3

I am not sure how to outline a function like this in R. Can someone outline the creation of a recursive function for the above numerical sequence?

I have been working with something like this:

myfunc <- function(x,n){
  if (n<0){
    print("please enter positive integer")
  } else {
    return(myfunc(n-1 + n-2 + n-3))
  }
}
myfunc (x = c(1, 2, 3), n = 3) #should return 3 (third number in sequence)
myfunc (x = c(1, 2, 3), n = 4) #should return 6 

This isn't a recursive function, but it will give you what you want:

myfunc <- function(x, n) sum(x[n - 1:n])

myfunc(1:3, 3) # 3
myfunc(1:3, 4) # 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM