While trying to implement nested for loops in a large dataframe, I realized that the nested for loops are not producing the results I expect. Here's an extract of my problem.
df <- data.frame(nrow = 20, ncol = 1)
df <- data.frame( LastPrice = c( 1221, 1220, 1220, 1217, 1216, 1218 , 1216, 1216, 1217, 1220, 1219, 1218, 1220, 1216, 1217, 1218, 1218, 1207, 1206, 1205))
for(j in 1:20) {for (i in 1:10) {df$SignalBinary[j] <- ifelse (df$LastPrice[j+i] == 1216, 1, 0)}}
I would expect and want the nested for loops to add SignalBinary vector to df dataframe with the following values: "1 1 1 1 1 1 1 1 1 1 NA NA NA NA NA NA NA NA NA NA"
Instead, df$SignalBinary becomes "0 0 0 1 0 0 0 0 0 0 NA NA NA NA NA NA NA NA NA NA"
Don't get it. Why is it registering only one 1216? Thank you very much!
You forget to sum up in the second loop, so it only matches when the last one i is 2016. Try this:
for(j in 1:20) {
tmp <- 0
for (i in 1:10)
tmp <- tmp + ifelse(df$LastPrice[j+i] == 1216, 1, 0)
df$SignalBinary[j] <- as.integer(tmp>0)
}
Or without a temp variable:
df$SignalBinary[j] <- 0
for(j in 1:20) {
for(i in 1:10)
df$SignalBinary[j] <- as.integer(df$SignalBinary[j] || ifelse (df$LastPrice[j+i] == 1216, 1, 0));
}