Solution to Exercise 1

See if you were right in exercise 1!

Before you start: an attempt at the exercise.
Setup: The vector definitions are included here so the solution runs from its top.
Your check: Compare your predictions and checks with one complete solution. Practise in the unit summary.

Task: Data about height and weight

Use c() to create the three vectors. Here, height is in metres, weight is in kilograms, and state contains the state labels in the same order as the exercise.

height <- c(1.67, 1.8, 1.58, 1.83, 1.65,
            1.74, 1.8, 1.6, 1.76, 1.8)
weight <- c(62, 78, 56, 85, 58, 70, 70, 120, 62, 90)
state <- c("NRW", "Bayern", "Sachsen", "Hessen", "Hessen",
           "MV", "Hessen", "Brandenburg", "Hessen", "Berlin")

Print each vector. Run the R commands; the separate output blocks show the results. Line wrapping may vary with the width of your R console.

height
 [1] 1.67 1.80 1.58 1.83 1.65 1.74 1.80 1.60 1.76 1.80
weight
 [1]  62  78  56  85  58  70  70 120  62  90
state
 [1] "NRW"         "Bayern"      "Sachsen"     "Hessen"      "Hessen"
 [6] "MV"          "Hessen"      "Brandenburg" "Hessen"      "Berlin"

Choose and inspect structures: one solution

Run the vector definitions above first. These are illustrative people; keep the order and units from the task.

people <- data.frame(height_m = height, weight_kg = weight,
                      state = factor(state))
str(people)
dim(people)
levels(people$state)
measurements <- cbind(height_m = height, weight_kg = weight)
dim(measurements)
typeof(measurements)
two_slices <- array(1:12, dim = c(2, 3, 2))
dim(two_slices)
profile <- list(people = people, units = c(height = "m", weight = "kg"))
length(profile)
str(profile)

people is 10-by-3, with two numeric columns and a factor with seven levels. measurements is a 10-by-2 double matrix; one row still represents one person. The array has two rows, three columns and two slices. profile has two components even though one is a ten-row table and the other contains two labels.

mixed_values <- c(height[1], state[1])
typeof(mixed_values)
mixed_table <- as.matrix(people)
typeof(mixed_table)
class(people$state)
as.numeric(people$state)
as.character(people$state)

Both combined objects use character storage. In mixed_table, the state labels are preserved as text, but numeric columns are also coerced to text and the factor class is lost. The factor’s numeric codes identify levels, not measurements or state names. Inspect labels with as.character(); there is no meaningful numeric state measurement to recover here.

Updated: