In the previous exercise you calculated the vector that contained the worldwide box office receipt for each of the three Star Wars movies. However, this vector is not yet part of star_wars_matrix
.
You can add a column or multiple columns to a matrix with the cbind()
function, which merges matrices and/or vectors together by column. For example:
big_matrix <- cbind(matrix1, matrix2, vector1 ...)
Add worldwide_vector
as a new column to the star_wars_matrix
and assign the result to all_wars_matrix
. Use the cbind()
function.
# Construct star_wars_matrix
box_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)
star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE,
dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),
c("US", "non-US")))
# The worldwide box office figures
worldwide_vector <- rowSums(star_wars_matrix)
# Bind the new variable worldwide_vector as a column to star_wars_matrix
all_wars_matrix <-
# Construct star_wars_matrix
box_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)
star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE,
dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),
c("US", "non-US")))
# The worldwide box office figures
worldwide_vector <- rowSums(star_wars_matrix)
# Bind the new variable worldwide_vector as a column to star_wars_matrix
all_wars_matrix <- cbind(star_wars_matrix, worldwide_vector)
msg <- "Do not change anything about the preset variables `box_office_all` and `star_wars_marix`!"
test_object("box_office", undefined_msg = msg, incorrect_msg = msg)
test_object("star_wars_matrix", undefined_msg = msg, incorrect_msg = msg)
test_object("worldwide_vector",
incorrect_msg = "Store the result of `rowSums(star_wars_matrix)` in `worldwide_vector`.")
msg <- "Have you correctly used `cbind()` to add `worldwide_vector` to `star_wars_matrix`? You should pass `star_wars_matrix` and `world_wide_vector` to `cbind()`, in this order. The resulting matrix, `all_wars_matrix`, should consist of three rows and three columns."
test_object("all_wars_matrix", incorrect_msg = msg)
success_msg("Nice job! After adding column to a matrix, the logical next step is adding rows. Learn how in the next exercise.");
In this exercise, you should pass two variables to cbind()
: star_wars_matrix
and worldwide_vector
, in this order. Assign the result to all_wars_matrix
.