GT213
GT213

Reputation: 99

How to perform calculations on each column of a data table in R

I'm very new to R and am getting starting with some simple calculation.

I have imported some data called BM_Returns, I am able to select a specific column and perform calculations on that column fine, how would i do it for all/a subset of the column?

example:

S1_Ann_ret <- (prod(1+(BM_Returns$Stock_1/100))^(1/yrs))-1

In my data column 1 is dates all other columns (2-15) are ones i would like to perform the above and other calculations on.

Thanks

Upvotes: 0

Views: 1923

Answers (1)

akrun
akrun

Reputation: 886938

If the calculation needs to be repeated, use across in mutate

libray(dplyr)
BM_Returns2 <- BM_Returns %>%
     mutate(across(2:15, ~ (prod(1 + (./100))^((1/yrs)) - 1))

Or use base R

BM_Returns[2:15] <- lapply(BM_Returns[2:15], function(x)
                (prod(1 + (x/100))^((1/BM_Returns$yrs)) - 1)

Upvotes: 1

Related Questions