Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将GBSVolatility应用于每行_R_Apply - Fatal编程技术网

R 将GBSVolatility应用于每行

R 将GBSVolatility应用于每行,r,apply,R,Apply,我有一个相当简单的问题,但不幸的是无法得出结果: 我想对data.frame的每一行应用GBSVolatility函数 我做了以下工作: > vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) > foo$iv <- apply(foo, 1, vol) 我想用隐含波动率做一个新专栏。我试着申请

我有一个相当简单的问题,但不幸的是无法得出结果: 我想对data.frame的每一行应用GBSVolatility函数

我做了以下工作:

> vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, 
r = 0.01, b = 0.02, maxiter = 500)
> foo$iv <- apply(foo, 1, vol)
我想用隐含波动率做一个新专栏。我试着申请

vol <- function(x) GBSVolatility(x["Price"], "c", S = 1000, x["Strike"], 
     Time = 1/4,  r = 0.01, b = 0.02, maxiter = 500)
foo$iv <- apply(foo, 1, vol)

vol您不应该使用
$
,因为apply给出的输入是命名向量,而不是data.frames。因此,这应该是可行的:

vol <- function(x) GBSVolatility(x["Price"], "c", S = 1000, x["Strike"], 
         Time = 1/4,  r = 0.01, b = 0.02, maxiter = 500)
foo$iv <- apply(foo, 1, vol)

如果数据框的一列或多列为字符,则在行上应用数据框将数字转换为字符。因此,简单的解决方法是在vol中再次转换:

vol <- function(x) GBSVolatility(as.numeric(x["Price"]), "c", S = 1000,    
  as.numeric(x["Strike"]), Time = 1/4, r = 0.01, b = 0.02, maxiter = 500)
apply(foo, 1, vol)

vol这是我能做的最好的了。它更“神奇”,但我认为目前为止最可读的选项是什么

foo <- read.table(textConnection("Date Price Strike Name
1.1  100   1200    X
1.1  120   1500    P"),header=TRUE)

foo$iv <- with(d,mapply(GBSVolatility,
              Price,Strike,
              MoreArgs=list(TypeFlag="c",S=1000,
                Time=1/4,r=0.01,b=0.02,maxiter=500)))

我想你的意思是“命名向量”,而不是“矩阵”。如果
foo
是一个标准数据帧,
x
将是一个带有名称属性的数值向量,而不是一个矩阵。@Gavin说得好,我已经从更多维度的情况中推断出了这一点。我会更新答案的。非常感谢,但不幸的是它不起作用。我必须以不同的方式编写函数吗?我更新了我的Q。
library(plyr)
vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, 
  Time = 1/4, r = 0.01, b = 0.02, maxiter = 500)
foo$iv <- adply(foo, 1, vol)$V1
foo <- read.table(textConnection("Date Price Strike Name
1.1  100   1200    X
1.1  120   1500    P"),header=TRUE)

foo$iv <- with(d,mapply(GBSVolatility,
              Price,Strike,
              MoreArgs=list(TypeFlag="c",S=1000,
                Time=1/4,r=0.01,b=0.02,maxiter=500)))