Skip to content
Prev 308349 / 398502 Next

For loop with i and j and multiple if statements... help!

Replace the y[1] with x[2] in the apply function - there is no 'y' defined in the function passed to apply. In the apply function, x is an 2-element vector representing a single row of the data (since the 1 in the second argument of apply says that it is applied row-wise). So the second element, i.e. x[2], is actually the y value. The name 'x' in function has nothing to do with the column 'x' in the data - it is the name of the argument sent to the function. 

Also, Sarah's code is vectorized (thus more elegant and efficient etc, and does not use a loop) so I suggest you stick with that.