# Fruit For-loops

Finally, we began talking about the often useful but often abused and misused construct of the for-loop.

The code we produced in class can be downloaded and reviewed here: Code-Day12.R

Consider the examples below:

#### the simplest of loops

# Creates a loop, repeating the print("Hello") command
# once for every element i in the sequence from 1 to 100.

for (i in 1:100) {

print("Hello")

}

# Creates a loop, repeating the print(i) command
# once for every element i in the sequence from 1 to 11.
# Each element of the sequence 1:11 is printed as R
# loops over it.

for (i in 1:11) {

print(i)

}

#### assignment inside of loops

# Creates an "empty" vector of length = 10, containing only NAs.

x <- rep(NA, times = 10)
x

# Creates a loop, repeating the i ^ 2 command
# once for every element i in the sequence from 1 to 10.
# The result of the i ^ 2 command is then assigned to the i'th
# element or location in the vector x as R loops over the
# sequence from i = 1 to i = 10.

for (i in 1:10) {

x[i] <- i ^ 2

}

# x now contains the squared values of the sequence from 1 to 10.

x

#### subsetting by way of loops

# Reads a version of the EPA's fuel economy data from this website
# into R as a data frame.

# The data frame has 1082 obs. and 28 vars.

dim(dat)

# Creates a vector containing the unique values of the vector named
# Manufacturer stored inside the data frame dat.

Car_Maker <- unique(dat\$Manufacturer)

# Counts the number of unique manufacturers.

n <- length(Car_Maker)

# Creates an empty vector of length n.

Mean_Engine_Size <- rep(NA, times = n)

# Creates a loop that for every i in the sequence from 1:10
# subsets the dataset dat, such that the values of the vector
# Manufacturer are equal to the i'th element in Car_maker. It then
# computes the average for the vector Displacement stored in the
# subset called temp, and finally stores the output in the i'th
# slot or position of the empty vector Mean_Engine_Size.

for (i in 1:n) {

temp <- subset(dat, dat\$Manufacturer == Car_Maker[i])
Mean_Engine_Size[i] <- mean(temp\$Displacement))

}

# The vector Car_Maker and Mean_Engine_Size are combined into or
# stored in a data frame called new_dat

new_dat <- data.frame(Car_Maker, Mean_Engine_Size)

new_dat