Saturday, 15 March 2014

r - using outer function to get a table of values returned by a user defined function -



r - using outer function to get a table of values returned by a user defined function -

i newbie in r , trying understand vector way of processing rather looping. need help how create table of values using outer function , user defined function.

following simple function gives cost of 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 create table of bond prices vector of yields, n , given value of c. 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 matrix/array of 18 prices (3x6), error

###### start of error message error in rep(c/freq, n * freq) : invalid 'times' argument in addition: warning message: in 1:(n * freq) : numerical look has 18 elements: first used #### end of error message

what doing wrong? , how desired answer?

please help.

regards

k

outer expecting function vectorized. written makes sense utilize bp when n scalar. rewrite bp function or take advantage of vectorize function 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 function vectorized # inquire vectorize 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 outer-join

No comments:

Post a Comment