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

前端 未结 1 1352
孤城傲影
孤城傲影 2021-01-21 21:27

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 de

1条回答
  •  不思量自难忘°
    2021-01-21 21:48

    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)
    

    0 讨论(0)
提交回复
热议问题