Selection of matrix elements

Similar to vectors, you can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors have one dimension, matrices have two dimensions. You should therefore use a comma to separate the rows you want to select from the columns. For example:

If you want to select all elements of a row or a column, no number is needed before or after the comma, respectively:

Back to Star Wars with this newly acquired knowledge! As in the previous exercise, all_wars_matrix is already available in your workspace.

Instruction

load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/all_wars_matrix.RData")) # all_wars_matrix is available in your workspace all_wars_matrix # Select the non-US revenue for all movies non_us_all <- # Average non-US revenue # Select the non-US revenue for first two movies non_us_some <- # Average non-US revenue for first two movies # all_wars_matrix is available in your workspace all_wars_matrix # Select the non-US revenue for all movies non_us_all <- all_wars_matrix[,2] # Average non-US revenue mean(non_us_all) # Select the non-US revenue for first two movies non_us_some <- all_wars_matrix[1:2,2] # Average non-US revenue for first two movies mean(non_us_some) 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) test_object("non_us_all", incorrect_msg = "Did you assign to `non_us_all` the entire second column of `all_wars_matrix`? You can use `[, 2]` to do this!") test_output_contains("mean(non_us_all)", incorrect_msg = "Have you calculated the average of the values in `non_us_all` by calling `mean(non_us_all)`? Simply print out the result.") test_object("non_us_some", incorrect_msg = "Did you assign to `non_us_some` the non-US revenue for the first two movies? You can use `[1:2,2]` to do this!") test_output_contains("mean(non_us_some)", incorrect_msg = "Have you calculated the average of the values in `non_us_some` by calling `mean(non_us_some)`? Simply print out the result.") success_msg("Nice one! Continue to the next exercise.")

You can select the entire second column of a matrix my_matrix with my_matrix[,2].

Previous: 3-7 | The total box office revenue for the entire saga

Next: 3-9 | A little arithmetic with matrices

Back to Main