Compute Delayed Column

I am sure there is an easier way to do this. I have the following data framework:

B <- c(1, 1, 1, 0, 1, 2, 2, 0, 0, 0)

A <- c(1:10)

df <- as.data.frame(cbind(A,B))

What I would like to do is add a third column (C) that applies column B if column B is not 0, in which case apply the percentage change in column A to the previous result of column C.

Here is what I did:

library(Hmisc)

df$New <- ifelse(df$B!=0, df$B, df$A/Lag(df$A, shift=1)*Lag(df$B, shift=1))

df$New2 <- ifelse(df$New !=0, df$New, df$A/Lag(df$A, shift=1)*Lag(df$New, shift=1))

df$New3 <- ifelse(df$New2 !=0, df$New2, df$A/Lag(df$A, shift=1)*Lag(df$New2, shift=1)) 

df$C <- pmax(df$New, df$New2, df$New3)  

df<- df[c(1,2,6)]

Essentially, I need to calculate by column based on the previous calculated result, so maybe sapply, but not sure.

+4
source share

Source: https://habr.com/ru/post/1669643/


All Articles