R 将GBSVolatility应用于每行
我有一个相当简单的问题,但不幸的是无法得出结果: 我想对data.frame的每一行应用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) 我想用隐含波动率做一个新专栏。我试着申请
> 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)))