3.6 Exercises

i2ds: Exercises

The following questions involve R data structures:

3.6.1 Why and when which data structure?

  1. 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?
  1. 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?
  1. 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.6.2 Saving data as list

In Section 3.4.2, we defined a data frame df to characterize five people as follows:

(df <- data.frame(name, gender, age))
#>     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 in df and ls.

  • 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 in df vs. in ls.)

  • Bonus: Can you save the data of df as a list ls_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.6.3 Manipulating matrices

Assuming a matrix mx:

(mx <- matrix(letters[1:4], nrow = 2, ncol = 2, byrow = TRUE))
#>      [,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)
mx_1  # transpose mx: 
#>      [,1] [,2]
#> [1,] "a"  "c" 
#> [2,] "b"  "d"

# (b)
mx_2  # mirror/swap rows of mx: 
#>      [,1] [,2]
#> [1,] "c"  "d" 
#> [2,] "a"  "b"

# (c)
mx_3  # mirror/swap columns of mx: 
#>      [,1] [,2]
#> [1,] "b"  "a" 
#> [2,] "d"  "c"

# (d)
mx_4  # swap only the elements of the 2nd column of mx: 
#>      [,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.6.4 Survey age

3.6.5 Exploring participant data

This concludes our first set of exercises on basic R data structures.