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
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