Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpreting "condition has length > 1" warning from `if` function

Tags:

r

if-statement

I have an array:

a <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 

and would like to implement the following function:

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

This function would like to check whether there is any value in a larger than 0 and if yes then divide each element by the sum of the total.

Otherwise it should just record 1.

I get the following warning message:

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

How can I correct the function?

like image 991
user1723765 Avatar asked Jan 05 '13 10:01

user1723765


People also ask

What does the condition has length 1 mean in R?

Let's call the function and pass the numeric vector as an argument: f(vec) Error in if (x > 0) { : the condition has length > 1. The error occurs because the vector has a length greater than one. The if() function can only check one element at a time.

How do you fix the condition has length 1 and only the first element will be used in R?

We can fix this error by using an ifelse() function. ifelse() function allows us to deal with each value at one time.

What does this the condition has length 1 and only the first element will be used mean in R?

How to Fix in R: the condition has length > 1 and only the first element will be used. This error occurs when you attempt to use an if() function to check for some condition, but pass a vector to the if() function instead of individual elements.


1 Answers

maybe you want ifelse:

a <- c(1,1,1,1,0,0,0,0,2,2) ifelse(a>0,a/sum(a),1)   [1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000  [9] 0.250 0.250 
like image 95
user1317221_G Avatar answered Sep 19 '22 00:09

user1317221_G