Warning: the condition has length > 1 and only the first element will be used

Total
0
Shares

R-lang throws the warning, the condition has length > 1 and only the first element will be used because if statement is not vectorized. In it’s place you need to use ifelse or you can use any() function.

Suppose you have a vector –

a <- c(1,2,3,0,0,4,5,0,0,1)

And you want to do an operation on it using if statement –

w<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

What we are trying to achieve is updating the values of vector a to value / sum of all values, if the value is greater than 0 otherwise set it to 1. So, the above vector should return –

// sum(a) = 1+2+3+0+0+4+5+0+0+1 = 16
a <- c(1/16, 2/16, 3/16, 1, 1, 4/16, 5/16, 1, 1, 1/16)

But the code will return a warning message –

 Warning message:
 In if (a > 0) { :
 the condition has length > 1 and only the first element will be used

Solution

There are 2 ways of doing this – using any() or ifelse

w <- function(a){
if (any(a>0)){
  a/sum(a)
}
  else 1
}
w <- function(a){
  ifelse(a>0,a/sum(a),1)
}

    Tweet this to help others

Live Demo

Open Live Demo