这是我正在尝试运行的代码,它需要一段时间。
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]
}
}
}
答案 0 :(得分:1)
不确定这是否有效,因为我无法测试它,但如果它有效,它应该会更快。
# get the indices
idx <- which(lm_data$DISTORGID == districts$DISTORGID & lm_data$gradeCode == districts$gradeCode)
lm_data$tentativeStartDate[idx] <- districts$firstDay[idx]