VISQL
VISQL

Reputation: 2048

Using the row position in an sapply function

This question is about sapply accessing the row number, of the row it's working on. I'm trying to use sapply (or whatever apply is applicable) instead of a loop. However, I need knowledge of which row I am working on during the apply. I can rewrite this, but I would like to do it with an apply function.

Finance: In a recombining binomial tree u >1, and d=1/u are multipliers to a stock price. To find the price at time n, you multiply: time zero price, u^#movements up, d^#of movements down. #down+#up=n

s_t = function(s_tm, tree_path, move_ratio, u_or_d ='u'){
    u.z = move_ratio
    if (u_or_d == 'd') { u.z = 1/move_ratio }
    ud_coeff = u.z ^ (tree_path[1]-tree_path[2])
    s_tm * ud_coeff }

This s_t will be the FUN function fed to sapply. the variable tree_path is a tuple/vector (#up,#down). For any time t, they always sum to the same number. However, I need #up and #down to change for each node in the tree.

Example: S0 = 100, u=1.25 d=1/u=0.8, t=3. Return the 4by1 matrix representing possible stock prices at time 3 (i.e. return S3)

S0 = 100; S1 = [125, 80]; S2=[156.25, 100, 64]; S3 = [195.3125, 125, 80, 51.2]

I would like to get S3, by calling sapply on an empty matrix, using s_T as the function to apply

prices = matrix(data=0, nrow =4, ncol=1)
stock_at_time_n = sapply(X = prices, 
    FUN = s_t, tree_path= (ROW#, LENGTH(prices) - ROW#), 
    move_ratio=1.25)

Result should be

[195.3125, 125, 80, 51.2]

Not concerned if it's a matrix, vector, etc at the moments, as I can just morph it with as.Whatever_I_want()

What is the correct notation for tree_path= (ROW#, LENGTH(prices) - ROW#) such that I can get the S3 output?

Upvotes: 0

Views: 233

Answers (1)

Jason Johnson
Jason Johnson

Reputation: 451

In general to access the index of an R object in an sapply loop you would use seq_along. Something like:

sapply(X = seq_along(prices),
       FUN = function(i) {
               s_t(s_tm=100, 
                   tree_path= c (i,length(prices)-i),
                   move_ratio = 1.25)
              })

Or really the way you are using sapply you could just use 1:n, where n = 4 in your case. Thanks and good luck!

Upvotes: 0

Related Questions