for each row of the column (foreach)

hello everyone,

I have a data frame. In column A I want each value from index 2 to be the result of the previous value A plus B divided by 10.
A[2:n]<- A[1:n]+B[2:n]/10

How can I do this with foreach?

C   B    A
1   11   0
2   12   1.2     (0+12/10)
3   13   2.5   (1.2+13/10)
> foreach (i=df$A[2:17],j=df$B[2:17])%do%
> {df$A[2:17]<-1:length(i)-1+1:length(j)/10
> }

But it doesn't work. Please help.

A clunky solution:

library(tidyverse)

tibble(
  "B" = c(11, 12, 13)
) %>% 
  mutate(A = cumsum(ifelse(row_number() == 1, 0, B / 10)))
1 Like

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.