Choices and Iteration
[] subsets a list and returns a list.[[ ]] and $ return the object inside the list.$ allows subsetting by name.TRUE.ifelse() is a vectorized if-else.Comparison Operator
A symbol that compares two values and returns a logical: TRUE if the comparison holds, FALSE otherwise.
<
>
<=
>=
==
!=
%in%
[1] TRUE FALSE TRUE FALSE
[1] TRUE TRUE
[,1] [,2]
[1,] 1 3
[2,] 2 4
If my bike is working
then I ride my bike to campus.
If my bike is not working and I have enough time
then I ride the bus to campus.
If my bike is not working and I don’t have enough time
then I take a cab.
sample() will randomly sample 1 element from the vector x.
if-then Statement
Executes a block of code only when a condition evaluates to TRUE; otherwise the block is skipped.
if-else Statement
Executes one block of code if a condition is met and a different block if it is not — exactly one branch always runs.
If my bike is working
then I ride my bike to campus.
If my bike is not working and I have enough time
then I ride the bus to campus.
If my bike is not working and I don’t have enough time
then I take a cab.
Using the R objects bike_working and enough_time, both logical vectors of length 1, write this decision tree in R using nested if-then statements and print().
02:30
For Loop
Repeats a block of code once for each element of a vector, with a loop variable taking each value in turn.
Goal: Build the first 10 elements of the Fibonacci Sequence.
[1] "x is positive :)"
[1] "element 3 is positive :)"
[1] "0.751262154884219 is positive :)"
ifelse()ifelse()
A vectorized if-else: applies a condition to every element of a vector at once, without an explicit loop.
An if-then statement is like a fork in the road: the computer will take one of two paths based on a condition.
TRUE.ifelse() is a vectorized if-else.