0

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"

  • "1" on first 10 rows because 1216 is present for each in at least one of the 10 rows below
  • "NA" on following 10 because for those the i loop extends outside the vector length

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!

2
  • What is your first line for? And also, what do you mean by because 1216 is present for each in at least one of the 10 rows below? Below what? Do you mean if 1216 is present in rows 11-20? Commented Apr 14, 2016 at 22:22
  • Guess first line not necessary. Meant present at least once in rows 02-11 for recording a 1 in row 1, at least once in rows 03-12 for recording a 1 in row 2 ... and at least once in rows 11-20 for recording a 1 in row 10. Thanks. Commented Apr 14, 2016 at 22:44

1 Answer 1

1

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));
        }
Sign up to request clarification or add additional context in comments.

1 Comment

I'm humbled. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.