if (condition) true_action
if (condition) true_action else false_action
(AST230) R for Data Science
In 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 switch
Loops allow you to repeatedly run code, typically with changing options
for
and while
if
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 greater than or equals 5"
When R evaluates the condition inside if
statements, it is looking for a logical element, i.e., TRUE
or FALSE
y = \begin{cases} A & \text{if} \;x >= 90 \\ B & \text{if} \;80 \leq x < 90 \\ C & \text{if} \;60 \leq x < 80 \\ F & \text{if}\;x < 60\end{cases}
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
\rightarrow a matrix or an array
MARGIN
\rightarrow 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
\rightarrow 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