简体   繁体   中英

Use previous calculated row value in r Continued 2

I have a data.table that looks like this:

library(data.table)
DT <- data.table(A=1:20, B=1:20*10, C=1:20*100)
DT
    A  B   C
1:  1  10  100
2:  2  20  200
3:  3  30  300
4:  4  40  400
5:  5  50  500
...
20: 20 200 2000

I want to be able to calculate a new column "R" that has the first value as

DT$R[1]<-tanh(DT$B[1]/400000)

, and then I want to use the first row of column R to help calculate the next row value of G.

DT$R[2] <- 0.5*tanh(DT$B[2]/400000) + DT$R[1]*0.6
DT$R[3] <- 0.5*tanh(DT$B[3]/400000) + DT$R[2]*0.6
DT$R[4] <- 0.5*tanh(DT$B[4]/400000) + DT$R[3]*0.6

This will then look a bit like this

    A    B   C       R
1:  1   10   100     2.5e-05
2:  2   20   200     4e-05
3:  3   30   300     6.15e-05
4:  4   40   400     8.69e-05
5:  5   50   500     0.00011464
...
20: 20  200  2000    0.0005781274

Any ideas on this would be made?

Is this what you are looking for ?

DT <- data.table(A=1:20, B=1:20*10, C=1:20*100)

DT$R = 0
DT$R[1]<-tanh(DT$B[1]/400000)


for(i in 2:nrow(DT)) {
  DT$R[i] <- 0.5*tanh(DT$B[i]/400000) + DT$R[i-1]*0.6
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM