使用外部函数获取用户定义函数返回的值表
我是 R 的新手,试图理解向量处理方式而不是循环方式。我需要有关如何使用外部函数和用户定义函数创建值表的帮助。
以下是一个简单的函数,它给出了普通债券的价格
bp = function(y, n=1, c=0, fv=100, freq=2){
per = 1:(n*freq)
cf = rep(c/freq, n*freq)
cf[length(cf)] = cf[length(cf)] + fv
df = 1/(1+y/freq)^per
cf %*% df
}
我想为收益率、n 和给定值 c 的向量创建一个债券价格表。像
ylds = c(0.05, 0.07, 0.08)
n = c(1, 5, 10, 15, 20,30)
price_table = outer(ylds, n, bp, c=9)
我预期有 18 个价格 (3x6) 的矩阵/数组,但我收到此错误
###### Start of Error Message
Error in rep(c/freq, n * freq) : invalid 'times' argument
In addition: Warning message:
In 1:(n * freq) : numerical expression has 18 elements: only the first used
#### End of Error Message
我做错了什么?我怎样才能得到想要的答案?
请帮忙。
问候
K
I am a newbie in R and trying to understand the vector way of processing rather than looping. I need help with how to create a table of values using outer function and a user defined function.
Following is a simple function which gives price of a trivial bond
bp = function(y, n=1, c=0, fv=100, freq=2){
per = 1:(n*freq)
cf = rep(c/freq, n*freq)
cf[length(cf)] = cf[length(cf)] + fv
df = 1/(1+y/freq)^per
cf %*% df
}
I would like to create a table of bond prices for a vector of yields, n and a given value of c. Some thing like
ylds = c(0.05, 0.07, 0.08)
n = c(1, 5, 10, 15, 20,30)
price_table = outer(ylds, n, bp, c=9)
I anticipate a matrix/array of 18 prices (3x6), but I get this error
###### Start of Error Message
Error in rep(c/freq, n * freq) : invalid 'times' argument
In addition: Warning message:
In 1:(n * freq) : numerical expression has 18 elements: only the first used
#### End of Error Message
What am I doing wrong? And how do I get the desired answer?
Please help.
regards
K
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
outer
期望您的函数被矢量化。正如它所写的,只有当 n 是标量时使用 bp 才有意义。您可以重写您的 bp 函数,或者您可以利用 Vectorize 函数来为您完成此操作。outer
is expecting your function to be vectorized. As it is written it only makes sense to use bp when n is a scalar. You could rewrite your bp function or you could take advantage of the Vectorize function which will do this for you.