R Programming Fundamentals

Dplyr Conditionals

Case_when

The case_when function is useful for vectorizing conditional statements. It is similar to
ifelse but can output any number of values, as opposed to just TRUE or FALSE. Here is an example of Case_when.

You need to have tidyverse and dplyr library installed to use these conditionals.

x <- 1:50 #selects all numbers from 1 to 50
case_when(
  x %% 35 == 0 ~ "fizz buzz",
  x %% 5 == 0 ~ "fizz",
  x %% 7 == 0 ~ "buzz",
  TRUE ~ as.character(x) #displays the number as it is if none of the condition is satisfied
)

Between

A common operation in data analysis is to determine if a value falls inside an interval. We can check this using conditionals. However, this can become cumbersome, especially within the tidyverse approach. The between function performs the same operation.

x <- 1:50
print ("The numbers between -15 to 15 in our dataset are:")
x[between(x, -15, 15)]

Bored With Data Science and want to upskill any other domain of your interest?