我有一个相当简单的问题,但遗憾的是无法得到结果:我想将GBSVolatility函数应用于我的data.frame的每一行。
我做了以下事情:
> 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)但这不起作用。 有人可以告诉我为什么吗?
非常感谢
达尼
更新:感谢您的建议。 我的数据框叫做foo,看起来像这样
Date Price Strike Name 1.1 100 1200 X 1.1 120 1500 P etc.我想创建一个隐含波动率的新列。 我试着申请,
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)但它没有奏效。
你有什么其他的建议? 谢谢
I have a rather simple question but unfortunately just cannot get to a result: I would like to apply the GBSVolatility function to each row of my data.frame.
I did the following:
> 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)But this does not work. Can someone tell me why?
Thanks alot
Dani
Update: Thank you for your suggestion. My data frame is called foo and looks like this
Date Price Strike Name 1.1 100 1200 X 1.1 120 1500 P etc.I would like to make a new column with the implied volatility. I tried to apply,
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)but it didn't work as well.
Do you have any other suggestions? Thanks
最满意答案
如果数据框的一列或多列是字符,则在行上申请数据框会将数字转换为字符。 如此简单的解决方法是再次转换为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)这不优雅。 我现在不记得更优雅的方式,可能使用d * ply或者其他东西......
可能这更优雅:
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)$V1applying for data frame on row converts numeric to character if one or more column of the data frame is character. So easy workaround is to convert again in 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)This is not elegant. I can not recall just now the more elegant way, probably using d*ply or something...
Probably this is more elegant:
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更多推荐
发布评论