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

Pieter Schoonees schoonees at ese.eur.nl
Thu Oct 18 18:09:59 CEST 2012

```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.

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of ingaschwabe
> Sent: Thursday 18 October 2012 4:51
> To: r-help at r-project.org
> Subject: Re: [R] For loop with i and j and multiple if statements...
> help!
>
> Dear all,
>
> Thanks for the many replies!
>
> Indeed, the function does not represent my explanation. It should have
> been:
>
> if (x[i] > 170 && x[i] < 1250 && y[j] > 150 && y[j] < 480)
>
> Sorry, my mistake.
>
> My data looks like this:
>     x   y
> 1 701 209
> 2 685 209
> 3 566 248
> 4 562 234
> 5 601 225
> 6 608 232
>
>
> Refering to the last post, I guess that my function then should look
> like something like this:
>
> test <- apply(input,1,function(x){
>               lookzone<-NULL
>               if (x[1] > 170 && x[1] < 1250 && y[1] > 150 && y[1] <
> 480)
>               {lookzone<-1}
>               if (x[1] > 170 && x[1] < 420  && y[1] > 480 && y[1] <
> 810)
>               {lookzone <- 2}
>               return(lookzone)
>               })
>
> however, when I run the function then nothing happens.
>
> and when I ask explicitly for the result then I get this
> > test
> NULL
>
> Can someone tell me what goes wrong here? Or give a hint?
> I'm not used to using the apply function and do use the for loop on the
> basis of an example that I once made so I am not a very experienced R
> user..
>
> Thank you so much for your help!
> I really appreciate it!
>
> Bye,inga
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/For-loop-
> with-i-and-j-and-multiple-if-statements-help-tp4646596p4646630.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

```