使用外部函数获取用户定义函数返回的值表 [英] using outer function to get a table of values returned by a user defined function

查看:49
本文介绍了使用外部函数获取用户定义函数返回的值表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的新手,并试图理解向量的处理方式而不是循环.我需要有关如何使用外部函数和用户定义函数创建值表的帮助.

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 是一个简单的函数,它给出了普通债券的价格

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
}

我想为收益率向量、n 和给定的 c 值创建一个债券价格表.类似的东西

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)

我预计会有一个包含 18 个价格 (3x6) 的矩阵/数组,但出现此错误

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?

请帮忙.

问候

K

推荐答案

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.

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)

这篇关于使用外部函数获取用户定义函数返回的值表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆