Sequential data.frame columns calculation using mutate

I've to execute a sequential formula in two data.frame columns, but the value of one column is the input to the other column and vice-versa. Besides, I need to get the value of the previous row to apply a conditional command.

This is an example of the dataframe I'm working on.

df <- data.frame(A=c(0.91,0.98,1,1.1), B=c(0.81, 1.11, 0.83, 0.92), C=c(0.09,0.06,0.09,0.08))
df$D <- NA
df$E <- NA
df[1,]$D <- 0.0

This is the output I'm expecting to get:

> df
     A    B    C          D          E
1 0.91 0.81 0.09 0.00000000 0.06971574
2 0.98 1.11 0.06 0.06971574 0.13029718
3 1.00 0.83 0.09 0.13029718 0.19051977
4 1.10 0.92 0.08 0.00000000 0.07073296

Basically, the value of column C depends on the values of column A of the previous row. If the previous row A is lower than 4, then C is equal to the value of column D on the row before. Otherwise, C is the result of the previous row A * B . The column D does not use the row before, but needs the result of column C to get the result of the formula: B - (B - D) * exp(-C) . Therefore, the first entry of column D is initialized with zero.

I think I could do it through dplyr::mutate, such as:

df %>%
    mutate(D = ifelse( lag(A) < 1, lag(E), lag(E) - lag(E) * lag(A)),
           E = B - (B - D) * exp(-C)
           )

But it does not really work as expected.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.