Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row by row computation

Tags:

r

I have started learning R.

Need your help on how to do this computation in loop:

C1    C2     C3   
A     5      10   
A     4       6
B     2       3
B     8       9

I would like the output as

C1    C2         C3     C4(c2*c3)
A     5          10     50
A     4+50=54     6      54*6= 324
B     2           3      6
B     8+6=14      9      14*9 = 126

For each distinct value in column C1 the value calculated at C4 should be added to the new row value at C2.

like image 758
Anshul S Avatar asked Mar 03 '23 18:03

Anshul S


1 Answers

One dplyr possibility could be:

df %>%
 group_by(C1) %>%
 mutate(C4 = (C2 + lag(C2 * C3, default = 0)) * C3,
        C2 = C2 + lag(C2 * C3, default = 0))


  C1       C2    C3    C4
  <chr> <dbl> <int> <dbl>
1 A         5    10    50
2 A        54     6   324
3 B         2     3     6
4 B        14     9   126

Or using data.table (by @markus):

setDT(df)[, `:=`(C4 = (C2 + shift(C2 * C3, fill = 0)) * C3,
                 C2 = C2 + shift(C4, fill = 0)), by = C1]
like image 115
tmfmnk Avatar answered Mar 20 '23 01:03

tmfmnk