I'd like to calculate data for two new columns in a data.frame where the results are based on the value of the previous row. However, the previous row also needs to be calculated, which means that there is a dependency between the two columns (the input for one calculation is based on the output of another calculation). I could do it through a for
, but maybe it's not the right way.
This is a sample for this case:
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
I've been trying it through dplyr::mutate.
df %>% mutate(D = ifelse( lag(A) < 1, lag(E), lag(E) - lag(E) * lag(A)), E = B - (B - D) * exp(-C) )
This is how the output should be:
> 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
https://stackoverflow.com/questions/65802170/how-to-use-mutate-result-as-input-to-calc-another-column-in-r-dplyr January 20, 2021 at 10:17AM
没有评论:
发表评论