r - 如何使用 R 中的下一个函数跳过 for 循环中的迭代
问题描述
len1 <- sample(1:2,100,replace=TRUE)
df <- data.frame(col1= c(1:200),col2= c(1:200))
for (i in 1:length(len1)) {
if (len1[i]==1) {
df$col1[i] <- len1[i] }
else if (len1[i]==2) {
df$col1[i] <- len1[i]
df$col1[i+1] <- 2
next
}
}
每次在 len1 列表中出现“2”时,我想在前一行中添加它并跳过下一次迭代 (i+1)。基本上,每次在 len1 列表中出现“2”时,我都会想要 (i+1)。
所需的最终表格将比 len1 样本长,它应该等于 sum(len1)。我希望它看起来像这样:每 2 后面跟着一个额外的 2。
> df
col1 col2
1 2 1
2 2 2
3 1 3
4 2 4
5 2 5
6 1 6
有什么建议么?谢谢!
解决方案
使用在设置时skip
始终重置为的变量FALSE
。
skip <- FALSE
for (i in 1:length(len1)) {
if (skip) {
skip <- FALSE
next
}
if (len1[i]==1) {
df$col1[i] <- len1[i]
} else if (len1[i]==2) {
df$col1[i] <- len1[i]
df$col1[i+1] <- 2
skip <- TRUE
}
}
推荐阅读
- php - 如何从关系 laravel 将列附加到模型
- sql - 如何计算一年中的滑动日计数SQL
- autodesk-forge - 在 Forge 中创建活动时出错 [严重]
- javascript - 如何在 jsPDF 中生成 utf-8 表?
- c++ - 如何将 SQlite 数据库连接到 devcpp?
- image-processing - 在指定像素上使用足迹的 2D 过滤器
- git - Git:恢复已添加但未提交的消失文件
- javascript - 根据int变量悬停在按钮组中的特定数量的按钮?
- javascript - 使用 IF 语句触发 onOpen
- azure-devops - 如何在 Azure DevOps 中使用 Gitlab 代码/项目