krthkskmr
krthkskmr

Reputation: 471

R, missing value where TRUE/FALSE needed

I trying to check if two variables have the same sign this is the code I am using.

a <- c(0)
x1 <- x/abs(x)
y1 <- y/abs(y)
if(x1==y1) {
  a <- x + y
  } else {
  a <- x - y
}

But I get the error

Error in if (x1 == y1) { : missing value where TRUE/FALSE needed

What am I doing wrong? Is there a more efficient way to check the signs?

Upvotes: 3

Views: 1883

Answers (1)

Gary Weissman
Gary Weissman

Reputation: 3627

Combining your operations together and using the sign function, you might try:

a <- ifelse(sign(x) == sign(y), x + y, x - y)

NB. sign(0) returns 0

Upvotes: 1

Related Questions