gpt4 book ai didi

r - 使用外部函数获取用户定义函数返回的值表

转载 作者:行者123 更新时间:2023-12-04 05:58:59 24 4
gpt4 key购买 nike

我是 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
}

我想为 yield 向量 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

我究竟做错了什么?我如何获得所需的答案?

请帮忙。

问候

最佳答案

outer期望您的函数被矢量化。正如它所写的那样,只有当 n 是标量时才使用 bp 才有意义。你可以重写你的 bp 函数,或者你可以利用 Vectorize 函数来为你做这件事。

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
}

# outer needs the function to be vectorized
# So we ask Vectorize to do this for us.
bpvec <- Vectorize(bp)
ylds = c(0.05, 0.07, 0.08)
n = c(1, 5, 10, 15, 20,30)
price_table = outer(ylds, n, bpvec, c=9)

关于r - 使用外部函数获取用户定义函数返回的值表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com