# Thread: what is wrong with my code

1. ## what is wrong with my code

I'm generating a random numbers x,y between -10 and 10
then I create an if statement to classify each pair(x,y) in 4 quadrant in the following if statement
but the column quad give me all 4

so why?

Code:
``````x <- runif(n=400, min = -10, max = +10)
y <- runif(n=400, min = -10, max = +10)
mydata=cbind(x,y)
mydata=as.data.frame(mydata)
plot(x,y)``````
Code:
``````for(i in 1:400){

if((0< mydata\$x[i] & mydata\$x[i] <10) & (0< mydata\$y[i] & mydata\$y[i] <10)){
}else
if((0<mydata\$x[i] & mydata\$x[i]<10) & (-10<mydata\$y[i] & mydata\$y[i]<0)){
}else
if((-10<mydata\$x[i] & mydata\$x[i]<0) & (-10<mydata\$y[i] & mydata\$y[i]<0)){
}else
if((-10<mydata\$x[i] &mydata\$x[i]<0) & (0<mydata\$y[i] & mydata\$y[i]<10)){
}}``````

2. ## Re: what is wrong with my code

I think you forgot to insert the "[i]" in "mydata\$quad[i]=1"

Code:
``````set.seed(2103) #if you repeat the code you will get the same numbers

x <- runif(n=400, min = -10, max = +10)
y <- runif(n=400, min = -10, max = +10)
mydata=cbind(x,y)
mydata=as.data.frame(mydata)
plot(x,y)

# initialize the variable

for(i in 1:400){

if((0< mydata\$x[i] & mydata\$x[i] <10) & (0< mydata\$y[i] & mydata\$y[i] <10)){
}else
if((0<mydata\$x[i] & mydata\$x[i]<10) & (-10<mydata\$y[i] & mydata\$y[i]<0)){
}else
if((-10<mydata\$x[i] & mydata\$x[i]<0) & (-10<mydata\$y[i] & mydata\$y[i]<0)){
}else
if((-10<mydata\$x[i] &mydata\$x[i]<0) & (0<mydata\$y[i] & mydata\$y[i]<10)){
}}

Maybe this help text that I copied somewhere some time ago can be helpful:

Spoiler:

An alternative (vectorized) method is:

Code:
``````mydata\$quad <-
ifelse(((0< mydata\$x & mydata\$x <10) & (0< mydata\$y & mydata\$y <10)), 1,
ifelse(((0<mydata\$x & mydata\$x<10) & (-10<mydata\$y & mydata\$y<0)),  2,
ifelse(((-10<mydata\$x & mydata\$x<0) & (-10<mydata\$y & mydata\$y<0)), 3,
ifelse(((-10<mydata\$x &mydata\$x<0) & (0<mydata\$y & mydata\$y<10)),  4, 9))))

Here there was no loop.

3. ## The Following User Says Thank You to GretaGarbo For This Useful Post:

trinker (10-31-2017)

 Tweet