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?
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.
We can fix this error by using an ifelse() function. ifelse() function allows us to deal with each value at one time.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With