Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in if (.) else { : the condition has length > 1

I am trying to group my data into three categories using the ifelse function.

Consider this hypothetical dataset and the application of ifelse:

a <- c(2,3,3,2)
b <- c(0,1,2,3)
df <- data.frame(a,b)

df %>%
if(a>2) {
print ('Hi')
} else if (a<3 & b<1) {
print ('Hello')
} else {
print ('Bye')
}

This error returned when I ran the code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in if (.) a>2 else { : the condition has length > 1

How should I fix it?

>Solution :

This works:

df %>%
  mutate(text = ifelse(a > 2, "Hi",
                       ifelse(a < 3 & b < 1, "Hello", "Bye")))
  a b  text
1 2 0 Hello
2 3 1    Hi
3 3 2    Hi
4 2 3   Bye
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading