简体   繁体   English

在具有递归形式的特定函数上使用R mapply()(用于)

[英]R mapply() on specific function with recursive form (using for)

I am working with some R code that I'm sure must be able to written using one of the apply series of functions, but I can't work out how. 我正在使用某些R代码,我确信它们必须能够使用apply系列函数之一来编写,但是我不知道该怎么做。 I have a dataframe with multiple columns and I want to call a function, and the input of the function is using multiple columns from the dataframe. 我有一个包含多列的数据框,我想调用一个函数,而函数的输入正在使用该数据框的多列。 Let's say I have this data and a function f: 假设我有此数据和一个函数f:

data<- data.frame(T=c(1,2,3,4), S=c(3,7,8,4), K=c(5,6,11,9))
data
V<-c(0.1,0.2,0.3,0.4,0.5,0.6)

f<-function(para_h,S,T,a,t,b){
  r<- V
  steps<-T
  # Recursive form: Terminal condition for the A and B at time T
  A_T=0
  B_T=0
  A=c()
  B=c()
  #  A and B a time T-1
  A[1]= r[steps]*a 
  B[1]= a*para_h[5]+ ((para_h[4])^(-2))         
  # Recursion back to time t      
  for (i in 2:steps){
    A[i]= A[i-1]+ r[steps-i+1]*a + para_h[1]*B[i-1]
    B[i]= para_h[2]*B[i-1]+a*para_h[5]+ (para_h[4]^(-2))
}
  f = exp(log(S)*a + A[t] + B[t]*b )

  return(f)
}

This function works well for some specific values : 此功能对于某些特定值效果很好:

> para_h<-c(0.1,0.2,0.3,0.4,0.5,0.7)
> f(para_h,S=3,T=2,a=0.4,t=1,b=0.1)
[1] 3.204144

I want to apply a function to each column S and T in a data frame. 我想对数据框中的每一列S和T应用一个函数。 So, my code looks like: 因此,我的代码如下所示:

mapply(function(para_h,S,T,a,t,b) f(para_h,S,T,a,t,b) ,para_h,S=data$S,T=data$T,a=0.4,t=1,b=0.1)

This gives an error: 这给出了一个错误:

> mapply(function(para_h,S,T,a,t,b) f(para_h,S,T,a,t,b) ,para_h,S=data$S,T=data$T,a=0.4,t=1,b=0.1)
Error in A[i] = A[i - 1] + r[steps - i + 1] * a + para_h[1] * B[i - 1] : 
  replacement has length zero

I'm pretty sure the problem is that : "steps" is vector. 我很确定问题是:“步骤”是向量。 Will really appreciate an elegant solution. 会非常感谢一个优雅的解决方案。 I hope this has made some sort of sense, any advice would be greatly appreciated. 我希望这具有某种意义,任何建议将不胜感激。

Couple of things: 几件事情:

1) each call of your function expects full para_h vector, but in your mapply code it will receive only one value at a time, so you probably wants something like this: 1)函数的每次调用都需要完整的para_h向量,但是在您的mapply代码中,一次只能接收一个值,因此您可能需要这样的代码:

 mapply(function(S,T) f(para_h,S,T,a=0.4,t=1,b=0.1), data$S, data$T)

or this: 或这个:

 apply(data,1,function(d) f(para_h,d['S'],d['T'],a=0.4,t=1,b=0.1))

2) Your function throws error when T==1 (which is the case in the first row of data ), so you might need to modify your sample data set to be able to run this code. 2)当T==1时,函数会引发错误(在data的第一行就是这种情况),因此您可能需要修改示例数据集才能运行此代码。

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

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