r - R:循环列表中的值
问题描述
我希望我的循环使用计算值作为索引,但它似乎不允许我这样做。
这是一个示例代码:
stype_rep <- c(6:10,11:15,31:35)
rep <- 6 #this can change
for (rep in stype_rep){
print(sprintf("rep start loop: %s",rep))
rep <- rep + 6 #this can change
print(sprintf("rep added: %s", rep))
}
运行代码时,它没有使用 is 的新rep
值rep + 6
。我怎么做?
迪西
解决方案
要在循环vector
外递归更改for
,您需要使用索引。请看下面的代码:
rep <- c(6:10, 11:15, 31:35)
for (i in seq_along(rep)[-1] - 1){
print(sprintf("rep start loop: %s",rep[i]))
rep[i + 1] <- rep[i] + 6 #this can change
print(sprintf("rep added: %s",rep[i]))
}
输出:
[1] "rep start loop: 6"
[1] "rep added: 6"
[1] "rep start loop: 12"
[1] "rep added: 12"
[1] "rep start loop: 18"
[1] "rep added: 18"
[1] "rep start loop: 24"
[1] "rep added: 24"
[1] "rep start loop: 30"
[1] "rep added: 30"
[1] "rep start loop: 36"
推荐阅读
- regex - 应该从 URL 中省略哪些字符以使其不被编码?(即更具人类可读性)
- ios - XCODE:UIView 背景没有出现在屏幕上,即使我在情节提要中设置了颜色并以编程方式
- java - 为什么我的工作没有显示我的转移工作
- r - 在 R 中标记重复项
- authorization - 检查权利/身份验证时在哪里解析资源所有者
- ruby-on-rails - 如何在rails应用程序中提交表单数据而不重新加载页面
- javascript - 混淆 forEach() 方法中参数的使用
- reactjs - 在 ReactJs 中将搜索词更改为小写
- reactjs - 将 React 代码库移动到 TypeScript 时出现问题
- angular - 如何链接多个 ngrx 选择器?