我正在撰写一个RMarkdown 文档,我希望重新运行一些代码块(5到9)。 这些代码块无需再次显示,因此我考虑使用
标签来结束它们。```{r echo=FALSE}
如另一个stackoverflow问题所述,使重新运行的代码块不可见是可以实现的。这样做很好,并输出所需结果(改进第二次迭代的拟合 - 在这里实现)。
然而,在理想情况下,代码应该是可展开的,以便用户可以在教育和清晰度方面看到发生了什么(例如,参见Greasemonkey解决方案的链接here),而不像我的第二个rpubs示例中隐藏起来。解决方案可能看起来像这样,但是周围的框要更短,避免分心:
for (i in 1:nrow(all.msim)){ # Loop creating aggregate values (to be repeated later)
USd.agg[i,] <- colSums(USd.cat * weights0[,i])
}
for (j in 1:nrow(all.msim)){
weights1[which(USd$age <= 30),j] <- all.msim[j,1] /USd.agg[j,1]
weights1[which(USd$age >= 31 & USd$age <= 50),j] <- all.msim[j,2] /USd.agg[j,2]
weights1[which(USd$age >= 51),j] <- all.msim[j,3] /USd.agg[j,3] ##
}
# Aggregate the results for each zone
for (i in 1:nrow(all.msim)){
USd.agg1[i,] <- colSums(USd.cat * weights0[,i] * weights1[,i])
}
# Test results
for (j in 1:nrow(all.msim)){
weights2[which(USd$sex == "m"),j] <- all.msim[j,4] /USd.agg1[j,4]
weights2[which(USd$sex == "f"),j] <- all.msim[j,5] /USd.agg1[j,5]
}
for (i in 1:nrow(all.msim)){
USd.agg2[i,] <- colSums(USd.cat * weights0[,i] * weights1[,i] * weights2[,i])
}
for (j in 1:nrow(all.msim)){
weights3[which(USd$mode == "bicycle"),j] <- all.msim[j,6] /USd.agg2[j,6]
weights3[which(USd$mode == "bus"),j] <- all.msim[j,7] /USd.agg2[j,7]
weights3[which(USd$mode == "car.d"),j] <- all.msim[j,8] /USd.agg2[j,8]
weights3[which(USd$mode == "car.p"),j] <- all.msim[j,9] /USd.agg2[j,9]
weights3[which(USd$mode == "walk"),j] <- all.msim[j,10] /USd.agg2[j,10]
}
weights4 <- weights0 * weights1 * weights2 * weights3
for (i in 1:nrow(all.msim)){
USd.agg3[i,] <- colSums(USd.cat * weights4[,i])
}
# Test results
plot(as.vector(as.matrix(all.msim)), as.vector(as.matrix(USd.agg3)),
xlab = "Constraints", ylab = "Model output")
abline(a=0, b=1)
cor(as.vector(as.matrix(all.msim)), as.vector(as.matrix(USd.agg3)))
#rowSums(USd.agg3[,1:3]) # The total population modelled for each zone, constraint 1
#rowSums(USd.agg3[,4:5])
#rowSums(USd.agg3[,6:10])
我对echo=F
的解决方案感到满意,但是如果有可扩展的代码片段,我将更加满意。
编辑:除了第一个以外,所有的RPubs示例现在都已被删除,以避免将本质上相同的文档堵塞到他们出色的出版系统中。