```{r}
# make example vector
num_vec = c(5, 10, 15, 20, 25, 30)
# Get the first element
num_vec[1]
# get the fifth element
num_vec[5]
# get the first and fourth element
num_vec[c(1, 4)]
```
[1] 5
[1] 25
[1] 5 20
Fall 2022
October 25, 2022
Understand the logic of iteration and how to use for loops
In R, vectors are ordered meaning that the position of each element is recorded and important.
Even single values are a vector!
We can interact with and subset vectors in a number of ways:
In R, iterating on something is working through a vector one element at a time.
Vector = c(2, 4, 6, 8, 10)
You can use iteration to apply the same process over multiple elements, like file paths.
You can tell R to read all of these files at once!
Create a cumulative sum and tell me if that gets above 10.
Vector = c(1, 2, 1, 3, 2, 5, 3, 1, 4)
for(X in Y) {
Do Z
}
For thing 1 in a sequence, do the following.
For thing 2 in sequence do the same.
For thing 3 in sequence do the same.
For thing 4 in sequence do the same.
For thing 5 in sequence do the same.
for(number in
c(3, 6, 9, 12, 15)) {
Add 5
}
For loops operate in whatever environment they are called in.
If called in the global environment, this means you can use any object in your global environment inside your for loop.
If inside a function, it will look for things inside the function first.
while(X == TRUE) {
Do Y
}
As long as X is TRUE, do Y.
Is X still TRUE? Do Y.
Is X still TRUE? Do Y.
Is X still TRUE? Do Y.
Is X still TRUE? Do Y.
Be sure your condition will change, or it will go on forever!
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] "And so on..."
[1] "I'm counting!"
[1] "1 one thousand!"
[1] "2 one thousand!"
[1] "3 one thousand!"
[1] "4 one thousand!"
[1] "5 one thousand!"
[1] "6 one thousand!"
[1] "7 one thousand!"
[1] "8 one thousand!"
[1] "9 one thousand!"
[1] "10 one thousand!"
```{r}
print("I'm counting!")
for(num in 1:10){
if(num == 6){next}
print(paste0(
num, " one thousand!"))
}
```
[1] "I'm counting!"
[1] "1 one thousand!"
[1] "2 one thousand!"
[1] "3 one thousand!"
[1] "4 one thousand!"
[1] "5 one thousand!"
[1] "7 one thousand!"
[1] "8 one thousand!"
[1] "9 one thousand!"
[1] "10 one thousand!"
Lists and Apply
SDS 192-03: Intro to Data Science