首页 > 解决方案 > R中的For循环-如何使用先前创建的值

问题描述

我在我的 data.table 对象的 if 语句中使用以下 for 循环。

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{}

所以我想做的是:如果 GDP 大于某个预定义的数字,我想每年在我的 data.table 对象中检查,如果是这样,那么我想通过将列值乘以 0.9 来更新列值。现在的问题是,如果我执行此循环,则循环正常工作,但我没有更新以前的值,但它始终采用导致事件的“默认”值,即我的所有值与发生事件的年份相同超过了我预定义的 GDP 数字。所以我的问题是:如何在循环中解决我之前计算的值?所以我希望“值”列中的值随着时间的推移慢慢下降。

插图:我想要的:

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.......
.
.
.

我得到什么:

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)

标签: rloopsfor-loopif-statementdata.table

解决方案


尝试这个:

# "For every country,"
for (j in unique(object$iso)) {

    # "each year..." (i.e., for every year...)
    for (i in unique(object$year[object$iso == j])) { 
        
        # "...if the GDP ['GDP_cap' in that year] is larger than a certain predefined number [i.e., 45000]..."
        if (object$GDP_cap[object$iso == j & object$year == i] > 45000) { 
            
            # "...then I want to update the ['eps'] column value by multiplying it [and all the 'eps' values in the coming years] by 0.9."
            object$eps[object$iso == j & object$year >= i] <- object$eps[object$iso == j & object$year >= i] * 0.9 
        }
    }
}

验证测试

这是一个较小的示例数据来尝试:

object <- object <- data.frame(
    iso = c("A", "A", "B", "B", "B"), 
    year = c(2001:2002, 2001:2003), 
    GDP_cap = c(1:2, 5:7), 
    eps = 1)

object
#  iso year GDP_cap eps
#1   A 2001       1   1
#2   A 2002       2   1
#3   B 2001       5   1
#4   B 2002       6   1
#5   B 2003       7   1


# for every iso...
for (j in unique(object$iso)) { 

    # for every year (in that iso)...
    for (i in unique(object$year[object$iso == j])) { 
        
        # if GDP_cap (in that iso and year) > 1...
        if (object$GDP_cap[object$iso == j & object$year == i] > 1) { 

            # then apply half-life decay to eps (in that iso and year as well as all coming years)
            object$eps[object$iso == j & object$year >= i] <- object$eps[object$iso == j & object$year >= i] * 0.5 
        }
    }
}

object
#  iso year GDP_cap   eps
#1   A 2001       1 1.000
#2   A 2002       2 0.500
#3   B 2001       5 0.500
#4   B 2002       6 0.250
#5   B 2003       7 0.125

我在这里改变了衰减率,因为做心算变得更容易了。
您可以看到“eps”衰减特定于每个“iso”。
object$eps[1]不改变。
object$eps[2]并且object$eps[3]是第一个“eps”,“GDP_cap”大于它们各自“iso”中分配的阈值,所以它们都是 1x0.5 1
object$eps[4]是第二个,object$iso == "B"所以它等于 1x0.5 2
object$eps[5]是第三个,所以它等于 1x0.5 3


推荐阅读