3.7 Exercises
The following questions involve R data structures:
3.7.1 Why and when which data structure?
- Compare and contrast atomic vectors with lists:
- What are their similarities and differences?
- Under which conditions should we use a list, rather than an atomic vector?
- Compare and contrast atomic vectors with matrices:
- What are their similarities and differences?
- Under which conditions should we use a matrix, rather than an atomic vector?
- Compare and contrast lists with data frames:
- What are their similarities and differences?
- Under which conditions should we use a list, rather than a data frame?
3.7.2 Saving data as a list
In Section 3.4.2, we defined a data frame df
to characterize five people as follows:
<- data.frame(name, gender, age))
(df #> name gender age
#> 1 Adam male 21
#> 2 Ben male 19
#> 3 Cecily female 20
#> 4 David male 48
#> 5 Evelyn misc 45
Save the same information as a list
ls
.Show how individual variables (e.g., the
age
vector) and values (e.g., Cecily’s age) can be accessed indf
andls
.Why would the data frame be a better choice of data structure here?
(Hint: Show how the entire information of a person could be accessed indf
vs. inls
.)Bonus: Can you save the data of
df
as a listls_2
in which every element contains all information of each person?
(Hint: As the information on a person contains different data types,ls_2
must by a list of lists.)
3.7.3 Manipulating matrices
Assuming a matrix mx
:
<- matrix(letters[1:4], nrow = 2, ncol = 2, byrow = TRUE))
(mx #> [,1] [,2]
#> [1,] "a" "b"
#> [2,] "c" "d"
Write R expressions that either apply functions or use some form of indexing to retrieve and replace individual elements for creating the following variants of the matrix mx
:
# (a)
# transpose mx:
mx_1 #> [,1] [,2]
#> [1,] "a" "c"
#> [2,] "b" "d"
# (b)
# mirror/swap rows of mx:
mx_2 #> [,1] [,2]
#> [1,] "c" "d"
#> [2,] "a" "b"
# (c)
# mirror/swap columns of mx:
mx_3 #> [,1] [,2]
#> [1,] "b" "a"
#> [2,] "d" "c"
# (d)
# swap only the elements of the 2nd column of mx:
mx_4 #> [,1] [,2]
#> [1,] "a" "d"
#> [2,] "b" "b"
Hint: This exercise could trivially be solved by creating the matrices mx_1
to mx_4
from scratch.
However, the purpose of the exercise is to use indexing for retrieving and replacing matrix elements.
3.7.4 Survey age
- See 1.8.7 Exercise 7
3.7.5 Exploring participant data
- See 1.8.8 Exercise 8
This concludes our first set of exercises on basic R data structures.