使用R来解决递归函数

时间:2015-02-24 05:23:33

标签: r recursion

我是R的新手,我尝试解决递归函数:给定

### creating variable R, a vector of length 10
R = c(-1.70, 0.61, -0.54, -2.40, -1.50, -1.07, -2.42, -1.62, -1.65, -1.58)  

然后有一个模型:R[t] = A(t) + 0.5*A(t-1) + 0.3*A(t-2),其中A(0) = A(-1) = 0,然后计算A(i),i = 1,2 ... 10。我编写了如下代码,但它总是给我错误,我不确定我错在哪里。请帮助我,非常感谢。

ma <- function(a){
                  r = NULL 
                  a = NULL
                  r[1]=1.70
                  r[2]=0.61
                  r[3]=-0.54
                  r[4]=-2.40
                  r[5]=-1.50
                  r[6]=-1.07
                  r[7]=-2.42
                  r[8]=-1.62
                  r[9]=-1.65
                  r[10]=-1.58
                  a[0] = 0
                  a[-1] = 0
                  for(i in 1:10){
                    r[i]=a[i]+0.5*a[i-1]+0.3*a[i-2]
                    return(a[i])
                  }
                 }

2 个答案:

答案 0 :(得分:0)

试试这个:

#define r with one call
r<-c(1.7, 0.61, -0.54, -2.4, -1.5, -1.07, -2.42, -1.62, -1.65, -1.58)
#initialize a with 12 values (its indices ranges from -1 to 10)
a<-numeric(12)
#set the first two elements of a to 0
a[1:2]<-0
#now solve for a[i], with i ranging from 3 to 12, corresponding to a_1,...,a_10
for (i in 3:12) a[i]<-r[i-2]-0.5*a[i-1]-0.3*a[i-2]
#get your values
a[3:12]
#[1]  1.7000000 -0.2400000 -0.9300000 -1.8630000 -0.2895000 -0.3663500
#[7] -2.1499750 -0.4351075 -0.7874537 -1.0557409

答案 1 :(得分:0)

您仍然可以使用功能。只需按原样编写递归函数A。

A <- function(n, r=c(1.70, 0.61, -0.54, -2.40, -1.50, -1.07, -2.42, -1.62, -1.65, -1.58)) {
  if (n<=0) {
    0
  } else {
    0.5 * A(n-1) + 0.3 * A(n-2) - r[n]
  }
}

> A(5)
[1] -0.2895