I'm trying to achieve something with nesting loops and if statements in R, not getting the desired results. Without wasting time with describing all the failed loops, these are my desired results:
- total loop = 50 times
- bigger loop with iterations of 1 : 10 and each time:
- within loop with iterations of 1 : 5, looping through a list (actually a column data$col)
- do something (change data$col[location 1...50]
-
check certain conditions, and write according values to those locations
-
overall: compare and check, is the current value in cell less than the next one, or are they both "a", then do X, otherwise, do Y.
- only compare if next value is 1:9
- store result at correct location data$newcolA[1...50]
- ideally, also store location of X happening in new column (data$newcolB)
So far I have:
myfun <- fun(abc){
a <- 0
b <- 1
for (i in 1:abc) {
for (j in 1:5) {
a <- a + 1 # count from 1 to 50
if ((b == 1) && (df$somecol[a] == 1)) {
data$newcolA <- 1
}
else if ((b == 1) && (df$somecol[a] == 0) && ())) {
data$newcolA <- 0
}
else if ((b > 1) && (df$somecol[a-1] < df$somecol[a])) {
data$newcolA <- 0
}
else if (((b > 1) && (df$somecol[a-1] == 1)) && (df$somecol[a] == 1)) {
data$newcolA <- 1
}
else if ((b > 1) && (df$somecol[a-1] == 1) && (df$somecol[a] == 0)) {
data$newcolA <- 0
}else {
break
}
}
}
}
myfun(10)
For solving the "only compare list items if the next one is not the last one of the 1:5 loop" I tried nesting in each if/else if: if (b < 5) { b <- (b + 1) a <- a + 1 } if (b == 5) { b <- 1 a <- a + 1 }
This didn't really work, in my console it seems as if the nesting of if-statements w/in the loop perform non-sequential checks (at least not iterating by 1).
Any tips appreciated!
Aucun commentaire:
Enregistrer un commentaire