首页 > 解决方案 > 如何使用 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 

有什么建议么?谢谢!

标签: rfor-loopif-statementnext

解决方案


使用在设置时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
  } 
}

推荐阅读