What's a matrix（矩阵）?
In R, a matrix is a collection of elements of the same data type (numeric, character, or logical) arranged into a fixed number of rows and columns. Since you are only working with rows and columns, a matrix is called two-dimensional（二维）.
You can construct a matrix in R with the
Consider the following example:
matrix(1:9, byrow = TRUE, nrow = 3)
- The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we use
1:9which is a shortcut（快捷方式） for
c(1, 2, 3, 4, 5, 6, 7, 8, 9).
- The argument
byrowindicates（表明） that the matrix is filled by the rows（行）. If we want the matrix to be filled by the columns（列）, we just place
byrow = FALSE.
- The third argument
nrowindicates that the matrix should have three rows.
- 注意这里都是 = 不是 = = ！！！
Analyzing matrices, you shall
It is now time to get your hands dirty. In the following exercises you will analyze the box office numbers of the Star Wars franchise（选举）. May the force（闹剧） be with you!
In the editor, three vectors are defined. Each one represents（展现） the box office numbers from the first three Star Wars movies. The first element of each vector indicates the US box office revenue（税收）, the second element refers to the Non-US box office (source: Wikipedia).
c(new_hope, empire_strikes, return_jedi)to combine the three vectors into one vector. Call this vector
- Construct a matrix with 3 rows, where each row represents a movie. Use the
matrix()function to this. The first argument is the vector
box_office, containing all box office figures. Next, you'll have to specify
nrow = 3and
byrow = TRUE. Name the resulting matrix
Naming a matrix
To help you remember what is stored in
star_wars_matrix, you would like
to add the names of the movies for the rows. Not only does this help you to read the data, but it is also useful to select certain（特定） elements from the matrix.
Similar to vectors, you can add names for the rows and the columns of a matrix
rownames(my_matrix) <- row_names_vector colnames(my_matrix) <- col_names_vector
titles. You will need these vectors to name the columns and rows of
colnames()to name the columns of
rownames()to name the rows of
- Print out
star_wars_matrixto see the result of your work.
Calculating the worldwide（世界范围的） box office
To calculate the total box office revenue for the three Star Wars movies, you have to take the sum of the US revenue column and the non-US revenue column.
In R, the function
calculates the totals for each row of a matrix. This function creates a new vector:
Adding a column for the Worldwide box office
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
You can add a column or multiple（多个） columns to a matrix with the
which merges（合并） matrices and/or vectors together by column. For example:
worldwide_vectoras a new column to the
star_wars_matrixand assign the result to
all_wars_matrix. Use the
Adding a row
Your R workspace, where all variables you defined 'live' (check out what a workspace is), has already been initialized and contains two matrices:
star_wars_matrixthat we have used all along, with data on the first trilogy（三部曲）,
star_wars_matrix2, with similar data for the second trilogy.
ls()in the console.
rbind()to paste together
star_wars_matrix2, in this order. Assign the resulting matrix to
The total box office revenue for the entire （完整）saga（故事）
- Calculate the total revenue for the US and the non-US region and assign （赋值）
total_revenue_vector. You can use the
- Print out
total_revenue_vectorto have a look at the results.
Selection of matrix elements
[ ]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（分离） that what to select from the rows from that what you want to select from the columns. For example:
my_matrix[1,2]selects the element at the first row and second column.
- 选择的是第一行，第二列 注意矩阵是二维的
my_matrix[1:3,2:4]results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.
my_matrix[,1]selects all elements of the first column.
my_matrix[1,]selects all elements of the first row.
all_wars_matrixis already available in your workspace.
- Select the non-US revenue for all movies (the entire second column of
all_wars_matrix), store the result as
non_us_allto calculate the average non-US revenue for all movies. Simply print out the result.
- This time, select the non-US revenue for the first two movies in
all_wars_matrix. Store the result as
mean()again to print out the average of the values in
A little arithmetic（计算） with matrices
Similar to what you have learned with vectors, the standard（标准） operators（运算符） like
etc. work in an element-wise way on matrices in R.
2 * my_matrixmultiplies each element of
all_wars_matrix. Assume that the price of a ticket was 5 dollars. Simply dividing the box office numbers by this ticket price gives you the number of visitors.
all_wars_matrixby 5, giving you the number of visitors in millions. Assign the resulting matrix to
- Print out
visitorsso you can have a look.
A little arithmetic with matrices (2)
2 * my_matrixmultiplied every element of
my_matrix1 * my_matrix2creates a matrix where each element is the product of the corresponding（相应） elements in
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_matrixto get the estimated（估计） number of US and non-US visitors for the six movies. Assign the result to
- From the
visitorsmatrix, select the entire first column, representing （描述）the number of visitors in the US. Store this selection as
- Calculate the average number of US visitors; print out the result.