youtube video link with explanations for these examples https://youtu.be/_2bbn2FG8To

Know the difference between both, how to use it and find out which one is faster.

Difference between ifelse and if_else

ifelse “comes from base r” if_else comes from dplyr

1

The first difference is that if_else is more strict. It checks if your true and false values are of same type or not this results in more predictable results In the example below we have used “Hi” as the true value which is a character string and we used 0 as the false value which is numeric. ifelse will run this code without any issues.

library(dplyr)
df <-  mtcars

df <- df%>%
  dplyr::mutate(Label = ifelse(hp > 100 ,"Hi","0"),
                NewWeight = wt * 2
  )

But if_else will result in an error as it expects both the true and false values to be of the same type

df <- df%>%
  dplyr::mutate(Label = if_else(hp > 100 ,"Hi","0"),
                NewWeight = wt * 2
  )
#The following code will give error as if_else requires that 
#the true and the false values should be of same type.
#We are using "Hi" as true value and  0 as false (which is numeric)
df <- df%>%
  dplyr::mutate(Label = if_else(hp > 100 ,"Hi",0),
                NewWeight = wt * 2
  )

2

We tested the timings for both the options and as as claimed in the documentation the if_else was faster.

#if_else is faster than ifelse

library(microbenchmark)



# Check timings for ifelse
microbenchmark(df <- df%>%
                 dplyr::mutate(Label = ifelse(hp > 100 ,"Hi",0)))


# Check timings for if_else
microbenchmark(df <- df%>%
                 dplyr::mutate(Label = if_else(hp > 100 ,"Hi",'0')))