我试图在R中编写一个涉及双“for”循环的函数,第二个“for”循环使用第一个“for”循环的参数。但是,当它进入第二个循环时,R似乎“忘记”第一个循环中定义的变量(例如“temp”和“i”)。
这是我的代码(错误行标有###):
pop.1996.mod <- data.frame(NULL)
number.of.expanded.rows <- 18
timeVec <- system.time(
for (i in 1:5){
cat("Working on row ",i," out of ",nrow(pop.1996.clean),".\n",sep="")
temp <- data.frame(matrix(0,number.of.expanded.rows,5))
temp[1] <- pop.1996.clean[i,1]
temp[2] <- pop.1996.clean[i,2]
#seifa code
position <- binarySearch(pop.1996.clean[i,1],postcodedata.1996.clean$pcode)
temp[5] <- postcodedata.1996.clean$seifa[position]
for (j in 3:(ncol(pop.1996.clean))
temp[j-2,3] <- pop.1996.clean[i,j]
### Error: unexpected symbol in:
### "for (j in 3:(ncol(pop.1996.clean))
### temp"
temp[j-2,4] <- sum(ihd.1996.clean$pcode==pop.1996.clean[i,1] && ihd.1996.clean$sex==pop.1996.clean[i,2] && ihd.1996.clean[,j]==1)
### Error in `[.data.frame`(pop.1996.clean, i, 1) : object 'i' not found
pop.1996.mod <- rbind(pop.1996.mod,temp)
### Error in rbind(pop.1996.mod, temp) : object 'temp' not found
}
)
cat("\n The time taken is", round(timeVec[3]), "seconds.\n\n")
谢谢。