Just like 2 * my_matrix
multiplied every element of my_matrix
by two, my_matrix1 * my_matrix2
creates a matrix where each element is the product of the corresponding elements in my_matrix1
and my_matrix2
.
After looking at the result of the previous exercise, big boss Lucas points out that the ticket prices went up over time. He asks to redo the analysis based on the prices you can find in ticket_prices_matrix
(source: imagination).
Those who are familiar with matrices should note that this is not the standard matrix multiplication for which you should use %*%
in R.
all_wars_matrix
by ticket_prices_matrix
to get the estimated number of US and non-US visitors for the six movies. Assign the result to visitors
.visitors
matrix, select the entire first column, representing the number of visitors in the US. Store this selection as us_visitors
.
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/all_wars_matrix.RData"))
movie_names <- c("A New Hope","The Empire Strikes Back","Return of the Jedi", "The Phantom Menace", "Attack of the Clones", "Revenge of the Sith")
col_titles <- c("US","non-US")
ticket_prices_matrix <- matrix(c(5, 5, 6, 6, 7, 7, 4, 4, 4.5, 4.5, 4.9, 4.9), nrow = 6, byrow = TRUE, dimnames = list(movie_names,col_titles))
# all_wars_matrix and ticket_prices_matrix are available in your workspace
all_wars_matrix
ticket_prices_matrix
# Estimated number of visitors
visitors <-
# US visitors
us_visitors <-
# Average number of US visitors
# all_wars_matrix and ticket_prices_matrix are available in your workspace
all_wars_matrix
ticket_prices_matrix
# Estimated number of visitors
visitors <- all_wars_matrix / ticket_prices_matrix
# US visitors
us_visitors <- visitors[ ,1]
# Average number of US visitors
mean(us_visitors)
msg <- "Do not change the contents of `all_wars_matrix`; this matrix has already been created for you in the workspace."
test_object("all_wars_matrix", undefined_msg = msg, incorrect_msg = msg)
msg <- "Do not change the contents of `ticket_prices_matrix`; this matrix has already been created for you in the workspace."
test_object("ticket_prices_matrix", undefined_msg = msg, incorrect_msg = msg)
test_object("visitors",
incorrect_msg = "Have you correctly created the `visitors` matrix? You should divide `all_wars_matrix` by `ticket_prices_matrix` to get there.")
test_object("us_visitors", incorrect_msg = "To create `us_visitors`, you should correctly select the entire first column from `visitors`. You can use `[,1]` for this!")
test_output_contains("mean(us_visitors)", incorrect_msg = "Once you have created `us_visitors`, you can use `mean()` to calculate the average number of visitors in the US. Make sure to print out the result.")
success_msg("It's a fact: the R force is with you! This exercise concludes the chapter on matrices. Next stop on your journey through the R language: factors.")
mean()
to calculate the average of the inputs to the function.visitors
using visitors[ ,1]
.