vendredi 13 septembre 2019

How to skip iterations in a for loop using the next function in R

ann <- 1:100
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
  } 
}

Every time "2" occurs in the len1 list, I would like to add this in the proceeding row and skip the next iteration (i+1). Basically, I would want (i+1) every time a "2" occurs in the len1 list.

This is the desired output:

> df
   col1 col2
1   2    1
2   2    2
3   1    3
4   2    4
5   2    5
6   1    6 

Any suggestions? Thanks!

Aucun commentaire:

Enregistrer un commentaire