Search code examples
rdataframeloopscalculated-columns

how how to add new columns to a dataframe based on an annual growth rate in r?


I would like to add 20 new columns to a dataframe with an annual growth rate, that is, generate projected data. It may be a bit of an easy question, however I am new to using r. I don't know if there is a way to do it with loops or another simpler way. I look forward to your support. My data is a data frame like this:

a <- c(1, 8, 10, 7)
b <- c("x1", "x2", "x3", "X4")
c <- c(10,20,30,40)
df <- data.frame(a,b,c)
d ```
considering a growth rate of 10% over column c, the expected result would be

   a  b  c  d    e     f   ...20 newcolumns 
1  1 x1 10 11  12.1  13.31 ...
2  8 x2 20 22  24.2  26.62 ...
3 10 x3 30 33  36.3  40.04 ...
4  7 X4 40 44  48.4  53.24 ...

Solution

  • In case you'll want to repeat the process several times you could use a function as follows (R Version 4.1.0)

    library(tidyverse)
    
    a <- c(1, 8, 10, 7)
    b <- c("x1", "x2", "x3", "X4")
    c <- c(10,20,30,40)
    df <- data.frame(a,b,c)
    
    
    f <- function(df, rate = 10, ncols = 20) {
      rate <- 1 + rate / 100
      dft <- as_tibble(df)
      
      for (i in seq_len(ncols)) {
        dft <- dft |> mutate(dft[[ncol(dft)]] * rate)
        
        if (ncols < length(letters) - ncol(df)) {
          colnames(dft)[[length(dft)]] <- letters[[length(dft)]]
        }
      }
      
      dft
    }
    f(df, rate = 10, ncols = 20)
    
    ## # A tibble: 4 x 23
    ##       a b         c     d     e     f     g     h     i     j     k     l     m
    ##   <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    ## 1     1 x1       10    11  12.1  13.3  14.6  16.1  17.7  19.5  21.4  23.6  25.9
    ## 2     8 x2       20    22  24.2  26.6  29.3  32.2  35.4  39.0  42.9  47.2  51.9
    ## 3    10 x3       30    33  36.3  39.9  43.9  48.3  53.1  58.5  64.3  70.7  77.8
    ## 4     7 X4       40    44  48.4  53.2  58.6  64.4  70.9  77.9  85.7  94.3 104. 
    ## # ... with 10 more variables: n <dbl>, o <dbl>, p <dbl>, q <dbl>, r <dbl>,
    ## #   s <dbl>, t <dbl>, u <dbl>, v <dbl>, w <dbl>