I'm having a hard time refactoring a for loop into a dplyr pipe. I need to reference the dataframa a and the previously calculated row. Any advice how to get b from a on a dplyr pipe?
Many thanks!
a <- tibble::tribble(~ 'a', ~ 'b', ~ 'c',
.1, .2, .3,
.2, .4, .6,
.3, .6, .9)
b <- a
for (i in 2:nrow(a)) {
b[i, ] <- b[i - 1, ] + b[i, ] * (1 - b[i - 1, ])
}
c <- a |>
dplyr::mutate(dplyr::across(where(is.numeric),
~ dplyr::lag(.x, 1, 0) +
.x *
(1 - dplyr::lag(.x, 1, 0))))
d <- a |> dplyr::rowwise( )|>
dplyr::mutate(dplyr::across(where(is.numeric),
~ dplyr::lag(.x, 1, 0) +
.x *
(1 - dplyr::lag(.x, 1, 0))))
identical(b,c)
identical(b,d)