mardi 17 novembre 2020

For Loop in R - How to use previously created value

I am using the following for loop within an if statement for my data.table object.

if (condition== "xxxx"){
    i=NULL
    for (i in seq(1,length(unique(object$year)),1)) {
      object[GDP>=xxxxx,value:=(value)*(0.9),by=c("iso")]
      i=i+1
    } else if .......
.
.
.
  } else{}

So what I want to do is: I want to check in every year in my data.table object if the GDP is larger than a certain predefined number and if so then I want to update the column value by multiplying it by 0.9. Now the problem is if I execute this loop the loop works and everything but I do not update the previous value but it always takes the "default" value which leads to the incident, that all of my values are the same from the year on which exceeds my predefined GDP number. So my question is: How to address my previously calculated value in a loop? So I want the the values in the column "value" so slowly decline over time.

Illustratation: What I want:

2020,xxxxx, 0.5
2025,xxxxx(predefined threshold reached ), 0.5*0.9(=0.45)
2030,xxxxx(predefined threshold reached), 0.45*0.9(0.405)
2035,xxxxx(predefined threshold reached), 0.405*0.9.......
.
.
.

What I get:

2025,xxxxx(predefined threshold reached ), 0.5*0.9(=0.45)
2030,xxxxx(predefined threshold reached ), 0.5*0.9(=0.45)
2035,xxxxx(predefined threshold reached ), 0.5*0.9(=0.45)

Aucun commentaire:

Enregistrer un commentaire