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

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'm trying to apply the GBM function of the sde package using the data in each row of the DataFrame:

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 to use apply but I think I'm wrong 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 apply in this case? Or any other way to apply this function in the columns highlighted above on all rows?

    
asked by anonymous 15.04.2016 / 21:34

1 answer

4

You could use apply in this case yes, the problem in your current code is this: within the apply the x that you are passing to your function is no longer a data.frame but a vector. That way, instead of x[,"PRICE"] you'd 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) 
})
    
16.04.2016 / 14:51