R log-transformation on dataframe -


i have dataframe (df) values (v) of different stocks @ different dates (t). new df profitability each time period. profitability is: ln(vi_t / vi_t-1) where:

ln natural logarithm

vi_t value of stock @ date t

vi_t-1 value of same stock @ date before

this output of df[1:3, 1:10]

      date    smi bond  abb addeco credit holcim nestle novartis roche 1 01/08/88 1507.5 3.63 4.98 159.20  15.62  14.64   4.01     4.59 11.33 2 01/09/88 1467.4 3.69 4.97 161.55  15.69  14.40   4.06     4.87 11.05 3 01/10/88 1538.0 3.27 5.47 173.72  16.02  14.72   4.14     5.05 11.94 

specifically, instead of 1467.4 @ [2, "smi"] want profitability ln(1467.4/1507.5) , same rest of values in dataframe. new r stuck. thinking of using mapply, , create transformation function myself. highly appreciated.

this compute profitabilities (assuming data in data.frame call d):

(d2<- log(embed(as.matrix(d[,-1]), 2) / d[-dim(d)[1], -1])) #          smi        bond          abb     addeco      credit      holcim     nestle   novartis       roche #1 -0.02696052  0.01639381 -0.002010051 0.01465342 0.004471422 -0.01652930 0.01239173 0.05921391 -0.02502365 #2  0.04699074 -0.12083647  0.095858776 0.07263012 0.020814375  0.02197891 0.01951281 0.03629431  0.07746368 

then, can add in dates, if want:

d2$date <- d$date[-1] 

alternatively, use apply based approach:

(d2 <- apply(d[-1], 2, function(x) diff(log(x)))) #             smi        bond          abb     addeco      credit      holcim     nestle   novartis       roche #[1,] -0.02696052  0.01639381 -0.002010051 0.01465342 0.004471422 -0.01652930 0.01239173 0.05921391 -0.02502365 #[2,]  0.04699074 -0.12083647  0.095858776 0.07263012 0.020814375  0.02197891 0.01951281 0.03629431  0.07746368 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -