Linked Questions

Popular Questions

The values of a cell in a data-frame depends on values in the preceding cells in the same column and values in another column. I am not sure how to update these dynamically. I am trying my best to show an example of what I am trying to achieve:

library(tidyverse)
set.seed(50)

df <- data_frame(SlNo = 1:12,
                 Scenario = rep(c(1, 2, 3),4),
                 A = round(rnorm(12, 11, 6)),
                 B = round(rnorm(12, 15, 4))) %>%
      arrange(Scenario) %>% mutate(C = 0, D = 0, E = A*B/2)

df<- add_row(df, .before = 1)

df$C[1] <- 4
df$E[1] <- 6

df$C[2] <- lag(df$C, 1)[2] * lag(df$E, 1)[2]


df$C[3] <- lag(df$C, 1)[3] * lag(df$E, 1)[3]

df

# A tibble: 13 x 7
    SlNo Scenario     A     B     C     D     E
   <int>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1    NA       NA    NA    NA     4    NA   6  
 2     1        1    14    13    24     0  91  
 3     4        1    14    14  2184     0  98  
 4     7        1    13    10     0     0  65  
 5    10        1     2    13     0     0  13  
 6     2        2     6    16     0     0  48  
 7     5        2     1    14     0     0   7  
 8     8        2     7    14     0     0  49  
 9    11        2    13     9     0     0  58.5
10     3        3    11    13     0     0  71.5
11     6        3     9    12     0     0  54  
12     9        3    17    14     0     0 119  
13    12        3    14    22     0     0 154 

I'd like each cell in column C dynamically update based on values in the preceding cells. Any help is greatly appreciated. Thank you very much in advance!!!

Related Questions