if (condition) true_action
if (condition) true_action else false_actionIn R, there are two primary tools of control flow: choices and loops
Choices allow you to run different code depending on the input
if statements and switchLoops allow you to repeatedly run code, typically with changing options
for and whileif statement in R as followstrue_action corresponds to the action for which the condition is true
false_action corresponds to the action for which the condition is false
#> [1] "x is smaller than 5"
When R evaluates the condition inside if statements, it is looking for a logical element, i.e., TRUE or FALSE
y={Aifx>=90Bif80≤x<90Cif60≤x<80Fifx<60
dplyr package has a function case_when() to categorize a variableif() function is used for single values.
To sort a list of values into two categories, you can use the base R function ifelse() or the dplyr package’s if_else() function
The syntax of if_else()
for loops are used to iterate over items in a vectorThe next statement skips the current iteration of the loop and starts the loop from the next iteration
The break statement terminate the execution of the loop.
A functional is a function that takes a function as an input and returns a vector as output.
apply() function takes a matrix or array as an input and return a lower dimensional summaryX → a matrix or an array
MARGIN → a vector giving the subscripts which the function will be applied over, e.g., for a matrix, 1 indicates a row and 2 indicates a column
FUN → the function to be applied on each MARGIN
A data frame should not be used as an input in apply()
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 4 7 10 13
#> [2,] 2 5 8 11 14
#> [3,] 3 6 9 12 15
lapply() returns a list after applying a function on each element of an R objectsapply() is similar to lapply() but it returns a atomic vector instead of a list#> $x
#> [1] 1 2 3
#>
#> $y
#> [,1] [,2]
#> [1,] 1 3
#> [2,] 2 4
