【问题标题】:Nested for-loop with if statement带有 if 语句的嵌套 for 循环
【发布时间】:2021-06-25 15:11:12
【问题描述】:

这是我正在尝试运行的代码,它需要一段时间。

Districts 是 39299 行 16 列的数据框,lm_data 是 59804 行和 16 个变量的数据框。我想在 lm_data 中设置一个名为 tentativeStartDate 的新变量,如果有几个条件,它会采用 districts$firstDay[j] 的值。有没有更有效的方法来做到这一点?

for (i in 1: nrow(lm_data)){
  for (j in 1: nrow(districts)){
    if (lm_data$DISTORGID[i] == districts$DISTORGID[j] & lm_data$gradeCode[i] == districts$gradeCode[j]){
      lm_data$tentativeStartDate[i] = districts$firstDay[j]
    }
  }
}

【问题讨论】:

标签: r for-loop if-statement


【解决方案1】:

不确定这是否可行,因为我无法对其进行测试,但如果确实可行,它应该会快得多。

# get the indices
idx <- which(lm_data$DISTORGID == districts$DISTORGID & lm_data$gradeCode == districts$gradeCode)

lm_data$tentativeStartDate[idx] <- districts$firstDay[idx]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多