Exercise 1

Try Exercise 1 yourself!

Before you start: R storage types; type checks and conversion.
Setup: No data files are needed. Create the objects on this page in the order shown.
Your check: Choose and inspect a table, matrix/array and list without separating observations. Practise in the unit summary.

Now it’s your turn.

Tasks

See the solution to the following task on the next page.

Task: Data about height and weight

Create three vectors named height, weight and state. For this exercise, interpret the heights in metres and the weights in kilograms; state contains German federal-state labels.

  • height (m): 1.67, 1.8, 1.58, 1.83, 1.65, 1.74, 1.8, 1.6, 1.76, 1.8
  • weight (kg): 62, 78, 56, 85, 58, 70, 70, 120, 62, 90
  • state: NRW, Bayern, Sachsen, Hessen, Hessen, MV, Hessen, Brandenburg, Hessen, Berlin

Each vector has ten entries. Entries in the same position belong to the same person, so keep the given order. Print each vector to inspect its contents.

Hint
Use the lowercase object names given above. Combine values with c(...). Write heights and weights as numbers, using a decimal point where needed, and put each state label in quotation marks.

Choose and inspect structures

Use the three ten-entry vectors above. Keep entries for each person together.

  1. Create people, a data frame with numeric columns height_m and weight_kg and a factor column state. Inspect str(), dim() and the levels; expect ten rows, three columns and seven state labels.
  2. Create a numeric matrix from just the height and weight vectors. Predict its dimensions and type, and explain why the mixed table is better kept as a data frame. Separately create an array from 1:12 with dimensions 2, 3, 2; what does each dimension count?
  3. Make a list containing people and a separate character vector naming the two measurement units. Predict the list’s length and why its components need not have equal lengths.
  4. Predict the type of c(height[1], state[1]) and as.matrix(people) before trying them. What meaning or type information needs care when combining numbers with labels? Explain why as.numeric(people$state) does not recover state names.
Hints

Use data.frame(), factor(), cbind(), array() and list(). The matrix has two numeric columns; the mixed table does not. A factor code points to a level label. str() and typeof() help check your predictions.

Self-check: every original height and weight still belongs to the same state entry. Compare with the worked solution after attempting the tasks; equivalent correct code is welcome.

Updated: