Apply a function using some columns of all rows of a Dataframe (r)

Asked

Viewed 723 times

4

I have the following Dataframe :

                AVG_VOLUME   AVG_RETURN  VOL     PRICE
SPX Index       500000       0.01        0.08    2082
KR7000270009    6000         0.02        0.09    102
KR7005930003    7000         0.02        0.08    103
JP3266400005    8000         0.03        0.08    104
KYG875721634    9000         0.04        0.08    105
JP3900000005    10           0.05        0.08    106

I am trying to apply the GBM function of the sde package using the data of each Dataframe line :

GBM(x=1, r=0, sigma=1, T=1, N=100)
Arguments
x initial value of the process at time t0.
r the interest rate of the GBM.
sigma the volatility of the GBM.
T final time.
N number of intervals in which to split [t0,T]

I tried applying but I believe I’m missing somewhere :

Test <- apply(Stock_Info,1,function(x) {
        GBM(x[,"PRICE"],x[,"AVG_RETURN"],x[,"VOL"],1,252) 
})

What is the correct way to apply in this case ? Or some other way to apply this function in the columns highlighted above in all rows ?

1 answer

4


You could use the apply in this case yes, the problem in your current code is as follows: apply the x that you are passing on to your function is no longer a data.frame rather a vector. Thus, instead of x[,"PRICE"] you would have to pass x["PRICE"] and so on.

Using your sample data:

Stock_Info <- read.table(text ="AVG_VOLUME   AVG_RETURN  VOL     PRICE
  500000       0.01        0.08    2082
    6000         0.02        0.09    102
    7000         0.02        0.08    103
    8000         0.03        0.08    104
    9000         0.04        0.08    105
    10           0.05        0.08    106", header = TRUE)


library("sde")
test <- apply(Stock_Info,1,function(x) {
  GBM(x["PRICE"],x["AVG_RETURN"],x["VOL"],1,252) 
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.