SavedByJESUS
SavedByJESUS

Reputation: 3314

How to create a binary variable from a loop and an if statement

Assuming I have a vector x containing 20 values between 0 and 2.

x = runif(20, 0, 2)

Now, I want to create another vector y (a binary variable) containing only 0 and 1 on the following condition: y = 0 if x < 1 and y = 1 in case x > 1.

I tried to do it with a loop and an if statement in the following way:

x = runif(20, 0, 2) # Create a vector of 20 values between 0 and 2
y = rep(5, 20) # Create a vector of 20 values (only 5's)

for(i in 1:length(x)) # Loop that assigns values to the y vector depending on x
{
  if(x < 1)
  {
    y[i] = 0
  }
  else
  {
    y[i] = 1
  }
}

But it unfortunately did not work as planned as my y vector ends up containing 0's only. What did I do wrong? Thank you :)

Upvotes: 4

Views: 2158

Answers (1)

NPE
NPE

Reputation: 500307

This can be done using vectorized operations instead of a loop:

> x <- runif(20, 0, 2)
> y <- as.integer(x > 1)
> x
 [1] 0.06553935 1.23221386 0.39982502 0.27821193 1.15281280 0.14248373 0.09206153 1.63555223 0.44962775 0.70711450
[11] 0.93994130 1.41955732 1.95790383 0.99646643 1.38737559 1.75813075 1.32844540 0.53076589 0.96152349 1.31173062
> y
 [1] 0 1 0 0 1 0 0 1 0 0 0 1 1 0 1 1 1 0 0 1

A more general solution is to use ifelse as it would allow you to use values other than zero and one:

> ifelse(x <= 1, -5, 5)
 [1] -5  5 -5 -5  5 -5 -5  5 -5 -5 -5  5  5 -5  5  5  5 -5 -5  5

Finally, it is worth noting that you can use more complex expressions with either of the two approaches:

> ifelse(x >= .5 & x <= 1.5, -5, 5)
 [1]  5 -5  5  5 -5  5  5  5  5 -5 -5 -5  5 -5 -5  5 -5 -5 -5 -5

Upvotes: 5

Related Questions