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

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)
}``````

## Live Demo

Demo might not work in private window (incognito)

Get only the best articles delivered to your mail

## error in file(file, “rt”) : cannot open the connection

R throws error in file(file, “rt”) : cannot open the connection, when it’s not able to find the file in the provided path. This could happen either due to wrong…

## R lang – Remove rows in dataframe

R lang provides the – operator to remove rows from dataframe. Simply provide the indexes of rows to remove with – sign. Consider this example – Here we have created…

## (list) object cannot be coerced to type ‘double’ – R Error

R-language throws error (list) object cannot be coerced to type ‘double‘ when we try to convert a list of string or other type values to a numeric vector. To correctly…

## %% in r language

%% in r language gives the modulus of two numbers. It is basically the remainder of division of first number by second number. Consider this code – Here we are…

## \$ operator is invalid for atomic vectors – R Error

Table of Contents Hide Check if vector is atomic or recursiveConvert vector to listLive DemoRelated Posts: In R language, you get the error, “\$ operator is invalid for atomic vectors”…