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

108 views

## Problem :

I am very new to r programming. I have the array and I want to implement the below method:

``````x<-function(b){
if (b>0){
b/sum(b)
}
else 1
}
``````

This method is written to check if there is any value which is larger than the 0 and if it says yes then it needs to divide each element by a sum of a total.

Or else it should just be 1.

But I face below warning message:

`“Warning message: r the condition has length > 1 and only the first element will be used”.`
`How can I fix the above error message?`

## Solution :

``I had also faced such kind of errors when I began programming. I can see your if` statement is currently not vectorized. To make it vectorized if statements you must use the `ifelse`. In your method you can write it as shown below:`
``````x <- function(b){
if (any(b>0)){
b/sum(b)
}
else 1
}``````

or you can try the short vectorised version as shown below

`ifelse(b > 0, b/sum(b), 1)`

It is upto you which way you want to use, as your first function gives you the output vector of length 1 (in the else part) and the `ifelse` gives you the output vector of length which is equal to length of `b`.

## Related questions

1 vote
408 views
Problem: I have limited knowledge of R and ggplot. I have recently written a function and trying to run the function as shown below: ggplot(datfr, aes(x = dat1[1:951,], y = dat2[1:951,])) + geom_point() After executing above function I am facing below error: Don't ... and when I try to use nrow on my two datasets it again returns the same number of rows. How can I fix above ggplot related error.