简体   繁体   English

一个序列的R中的递归function

[英]Recursive function in R of a sequence

I am trying to write a function that takes X and n, and returns element Xn.我正在尝试编写一个采用 X 和 n 并返回元素 Xn 的 function。 X is a vector of the first 3 elements of the sequence and n is a positive integer. X 是序列的前 3 个元素的向量,n 是正 integer。 Xn = Xn-1 + Xn-2 - Xn-3 Xn = Xn-1 + Xn-2 - Xn-3

I am not sure how to outline a function like this in R.我不确定如何在 R 中像这样概述 function。 Can someone outline the creation of a recursive function for the above numerical sequence?有人可以概述为上述数字序列创建递归 function 吗?

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:这不是递归 function,但它会给你你想要的:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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