如何修改我的代码以更新循环内的变量?更新R中循环内的变量
具体来说,我想要做的东西像下面这样:
myMatrix1 <- read.table(someFile)
myMatrix2 <- read.table(someFile2)
for (i in nrow(myMatrix2))
{
myMatrix3 <- myMatrix1[which(doSomeTest),]
myMatrix4 <- rep(myMatrix2$header1,nrow(myMatrix1))
myMatrix5 <- rep(myMatrix2$header2, nrow(myMatrix1))
myMatrix6 <- cbind(myMatrix3, myMatrix4, myMatrix5)
# *see question
}
我怎样才能myMatrix6进行更新,而不是重新分配的cbind(myMatrix3, myMatrix4, myMatrix5)
的产品?换言之,如果在第一次迭代(i = 1),得到的myMatrix6:
> 1 1 1 1
> 2 2 2 2
和第二次迭代(i = 2),得到的myMatrix的6:
> 3 3 3 3
> 4 4 4 4
如何获取的数据帧:
> 1 1 1 1
> 2 2 2 2
> 3 3 3 3
> 4 4 4 4
UPDATE:(?)
我已经 - 拜迪文和蒂莫的建议 - 有后续ING。但是,下面的代码使我在我的数据集上运行了大约2个小时。有什么方法可以让它跑得更快? (不使用更强大的电脑我可以补充)
# create empty matrix for sedimentation
myMatrix6 <- data.frame(NA,NA,NA,NA)[0,]
names(myMatrix6) <- letters[1:4]
# create empty matrix for bore
myMatrix7 <- data.frame(NA,NA,NA,NA)[0,]
names(myMatrix7) <- letters[1:4]
for (i in 1:nrow(myMatrix2))
{
# create matrix that has the value of myMatrix1$begin being
# situated between the values of myMatrix2begin[i] and myMatrix2finish[i]
myMatrix3 <- myMatrix1[which((myMatrix1$begin > myMatrix2$begin[i]) & (myMatrix1$begin < myMatrix2$finish[i])),]
myMatrix4 <- rep(myMatrix2$sedimentation, nrow(myMatrix3))
if (is.na(myMatrix2$boreWidth[i])) {
myMatrix5 <- rep(NA, nrow(myMatrix3))
}
else if (myMatrix2$boreWidth[i] == 0) {
myMatrix5 <- rep(TRUE, nrow(myMatrix3))
}
else if (myMatrix2$boreWidth[i] > 0) {
myMatrix5 <- rep(FALSE, nrow(myMatrix3))
}
myMatrix6 <- rbind(myMatrix6, cbind(myMatrix3, myMatrix4))
myMatrix7 <- rbind(myMatrix7, cbind(myMatrix3, myMatrix5))
}
你没有明确说明这些不同的物体有什么关系。 “someVector”在某种程度上与“myMatrix1”有关吗?同样,什么是“someArg”?而赋值给“myMatrix2”将取代它,而不是附加到它。我怀疑你对R做了不正确的声明,因为它不是某种其他语言。 –
_我怀疑你对R有不正确的说法,因为它不是其他语言我不怀疑它。这就是为什么我说_seems_。无论如何,感谢您的有用评论。 – Kaleb
@Kaleb我已编辑您的问题,删除煽动性措辞。请检查是否正确。 – Andrie