Below I made a list of small practice problems that you can test out. I provide helpful information here and there, and I encourage you to use google to your advantage to get used to going on Stack Exchange or other coding Q&A websites to help you figure out these problems.
R provides many functions to examine features of vectors and other objects, for example
class() - what kind of object is it (high-level)?
typeof() - what is the object’s data type (low-level)?
length() - how long is it? What about two dimensional objects?
attributes() - does it have any metadata?
Check out this quick read to understand the more subtle nuances of data types and structure in R: http://uc-r.github.io/integer_double/.
Problem 1.
Write a for loop that iterates over the numbers 1 to 7 and prints the cube of each number as a string using print().
# https://swcarpentry.github.io/r-novice-inflammation/13-supp-data-structures/
v <- c(1L:7L)
vc <- 0
for(i in v) {
vc[i] <- as.character(v[i]*v[i]*v[i])
}
print(vc)
## [1] "1" "8" "27" "64" "125" "216" "343"
Problem 2.
Using a for loop, simulate flipping a coin twenty times, keeping track of the individual outcomes (1 = heads, 0 = tails) in a vector that you preallocte. Hint: you will need to use the sample() function; it takes a sample of the specified size from the elements of x using either with or without replacement.
# One way to do it:
n <- 20
coin_outc <- vector(length = n, mode = "integer")
for (i in 1:20) {
coin_outc[i] <- sample(c(0L, 1L), 1) # (x, n) x = vector, n = sample size
}
coin_outc
## [1] 0 1 0 1 0 0 0 0 1 1 1 0 1 0 1 1 0 0 0 0
# Alternative way
coin <- c('heads', 'tails')
flip <- sample(coin, size=20, replace=TRUE)
coin_outcome <- vector(length = 0, mode = "integer")
for (i in flip) {
coin_outcome <- c(coin_outcome, i)
}
print(coin_outcome)
## [1] "tails" "tails" "heads" "heads" "tails" "heads" "tails" "heads" "tails"
## [10] "tails" "tails" "tails" "tails" "heads" "tails" "heads" "heads" "heads"
## [19] "heads" "heads"
Problem 3.
Given 10 double-digit integers, reverse their digits. (e.g. 25 becomes 52, 34 becomes 43, etc.). Be creative with your datatypes to make manipulating the numbers more flexible! Also, keep in mind the different ways in which you can append a value to a vector:
Here are several ways to do it.
one way
for (i in 1:length(values)) vector[i] <- values[i]
another way for (i in 1:length(values)) vector <- c(vector, values[i])
yet another way (there are many ways)
for (v in values) vector <- c(vector, v)
double_digs <- c(25, 34, 62, 89, 14, 31, 57, 93, 86, 43)
# One way to do it:
vector <- vector()
for (i in 1:length(double_digs)){
vector <- c(vector, floor(double_digs[i]/10) + (double_digs[i] %% 10)*10)
}
print(vector)
## [1] 52 43 26 98 41 13 75 39 68 34
# Alternative way to do it:
reverse_digs <- c()
for (n in double_digs) {
as.character(n)
first_digit <- substr(n, 1,1)
last_digit <- substr(n, 2,2)
reverse_n <- paste(last_digit, first_digit, sep="")
reverse_digs <- c(reverse_digs, as.numeric(reverse_n))
}
reverse_digs
## [1] 52 43 26 98 41 13 75 39 68 34
Problem 4
Using the following variables:
x=1
i=c(1:10)
Write a for() loop that increments x by two for each i. Look back at Lesson 3 for help!
x=1
i=c(1:10)
for (n in i) {
x <- x + 2
}
print(x)
## [1] 21
Problem 5
Using the following variables:
x=1
y=40
i=c(1:10)
Write a for() loop that increments x by three and decrease y by two, for each i.
x=1
y=40
i=c(1:10)
for (n in i) {
x <- x + 3
y <- y - 2
}
print(x)
## [1] 31
print(y)
## [1] 20
Problem 6
Edgar Anderson’s Iris Data. This data can be loaded into R directly into the R command line. This famous (Fisher’s or Anderson’s) iris data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.
Like in lessons 1 and 2, do some quick data exploration. Then, use a for loop to sum up the petal widiths for all the species using a counter. Remember you will need to iterate over the rows in a specific column! Check your answer for that column afterwards by using the sum() function.
total_petal_width <- 0
for (w in iris$Petal.Width) {
total_petal_width <- total_petal_width + w
}
print(total_petal_width)
## [1] 179.9
print(sum(iris$Petal.Width))
## [1] 179.9
Problem 7
Southern and Northern hemispheres split. Write a for loop that sperates cities into northern and southern hemispheres. Hint: make sure you understand the structure of list vs. vector and their indicies, so make lots of print statemetns!
NY_coor <- c(40.7128, -74.0060)
Paris_coor <- c(48.8566, 2.3522)
London_coor <- c(51.5074, -0.1278)
Tokyo_coor <- c(35.6762, 139.6503)
RiodeJaneiro_coor <- c(-22.9068, -43.1729)
CapeTown_coor <- c(-33.9249, 18.4241)
coors <- list(NY_coor, Paris_coor, London_coor, Tokyo_coor, RiodeJaneiro_coor, CapeTown_coor)
coors
## [[1]]
## [1] 40.7128 -74.0060
##
## [[2]]
## [1] 48.8566 2.3522
##
## [[3]]
## [1] 51.5074 -0.1278
##
## [[4]]
## [1] 35.6762 139.6503
##
## [[5]]
## [1] -22.9068 -43.1729
##
## [[6]]
## [1] -33.9249 18.4241
north_hem <- c()
south_hem <- c()
for (coor in coors) {
lat <- coor[1]
if (lat > 0)
north_hem <-c(north_hem, list(coor))
if (lat < 0)
south_hem <-c(south_hem, list(coor))
}
print(north_hem)
## [[1]]
## [1] 40.7128 -74.0060
##
## [[2]]
## [1] 48.8566 2.3522
##
## [[3]]
## [1] 51.5074 -0.1278
##
## [[4]]
## [1] 35.6762 139.6503
print(south_hem)
## [[1]]
## [1] -22.9068 -43.1729
##
## [[2]]
## [1] -33.9249 18.4241
Problem 8
Eastern and Western hemispheres split. Write a for loop that sperates cities into eastern and western hemispheres.
east_hem <- c()
west_hem <- c()
for (coor in coors) {
lon <- coor[2]
if (lon > 0)
east_hem <-c(east_hem, list(coor))
if (lon < 0)
west_hem <-c(west_hem, list(coor))
}
print(east_hem)
## [[1]]
## [1] 48.8566 2.3522
##
## [[2]]
## [1] 35.6762 139.6503
##
## [[3]]
## [1] -33.9249 18.4241
print(west_hem)
## [[1]]
## [1] 40.7128 -74.0060
##
## [[2]]
## [1] 51.5074 -0.1278
##
## [[3]]
## [1] -22.9068 -43.1729
Problem 9
Create an exponential function by using the polynomial of x between 1 and 4 and then store it in a list. Hint: look up the seq() function to create a range to iterate over. Also, look at its other arguments as well (e.g. type in seq(1,4) and then seq(1,4,2) to see what is happening).
Your output should be a list with numbers that grow exponentially:
1 4 9 16
# Create an empty list
list <- c()
# Create a for statement to populate the list
for (i in seq(1, 4, by=1)) {
list[[i]] <- i*i
}
print(list)
## [1] 1 4 9 16
Problem 10.
Use a for loop to add 5 to each odd index in the list and 10 to every even index in the following list. Hint: use seq(l) to iterate/loop over indicies, not values of the list.
l = c(5, 10, 25, 30, 35, 40)
for (i in seq(l)) {
if (i%%2 == 1) {
l[i] <- l[i] + 5 }
if (i%%2 == 0) {
l[i] <- l[i] + 10 }
}
print(l)
## [1] 10 20 30 40 40 50