0

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

GT213
  • 89
  • 6
  • Please explain what `yrs` means in this. Is it just a constant? For future questions please consider posting a reproducible example https://stackoverflow.com/help/minimal-reproducible-example – Bernhard Sep 01 '21 at 20:29
  • Does this answer your question? [Summarizing multiple columns with data.table](https://stackoverflow.com/questions/16513827/summarizing-multiple-columns-with-data-table) – Bernhard Sep 01 '21 at 20:31
  • This contains a good answer: https://stackoverflow.com/q/16513827/6503141 – Bernhard Sep 01 '21 at 20:31
  • Yes yrs is a constant. I'm taking a look at the answer you posted right now. I tried Akrun's solution but i am having trouble installing dplyr – GT213 Sep 01 '21 at 20:44
  • It might be helpfull to state whether you have an actual `data.table` as the heading suggest or a classic `data.frame` or a `tibble`. Nothing beats a reproducible example... – Bernhard Sep 01 '21 at 20:48
  • Yes it is a data table, here is a subset of it that will hopefully work for an example: Date R200V Index R200G Index RMV Index RDG Index RUJ Index RUO Index 1: 12/31/2020 3.4070 4.5583 4.6230 4.7972 7.9204 9.3442 2: 11/30/2020 13.1444 9.5536 14.0415 13.4312 19.2901 17.6272 3: 10/30/2020 -2.4472 -4.1229 0.9304 0.1226 3.5765 0.7598 4: 9/30/2020 -2.5523 -5.3517 -2.2652 -1.4003 -4.6532 -2.1429 5: 8/31/2020 4.2237 11.9387 3.9595 2.7206 5.3871 5.8662 – GT213 Sep 01 '21 at 21:04

1 Answers1

1

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, i cannot get dplyr installed and running correctly this is the error i am getting: ``` > library("dplyr") Error: package or namespace load failed for 'dplyr' in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]): there is no package called 'lifecycle' ``` I think it might be due to a lack of permissions on my computer but am not sure. – GT213 Sep 01 '21 at 20:45
  • @GT213 then, try with the `base R` updated solution – akrun Sep 01 '21 at 20:47