R语言从基础入门到提高(四)matrices(矩阵)
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 matrix() function. 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(快捷方式) forc(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 placebyrow = 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).
- Use
c(new_hope, empire_strikes, return_jedi)to combine the three vectors into one vector. Call this vectorbox_office. - Construct a matrix with 3 rows, where each row represents a movie. Use the
matrix()function to this. The first argument is the vectorbox_office, containing all box office figures. Next, you'll have to specifynrow = 3andbyrow = TRUE. Name the resulting matrixstar_wars_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
region, and titles. You will need these vectors to name the columns and rows of star_wars_matrix, respectively.- Use
colnames()to name the columns ofstar_wars_matrixwith theregionvector. - Use
rownames()to name the rows ofstar_wars_matrixwith thetitlesvector. - 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 rowSums() conveniently(方便的)
calculates the totals for each row of a matrix. This function creates a new vector:
rowSums(my_matrix)worldwide_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 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 ...)worldwide_vector as
a new column to the star_wars_matrixand
assign the result to all_wars_matrix.
Use the cbind() function.Adding a row
Just like every action has a reaction, every cbind() has
an rbind().
(We admit, we are pretty bad with metaphors.)
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_matrix and star_wars_matrix2,
in this order. Assign the resulting matrix to all_wars_matrix.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 thecolSums()function. - 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_matrix is
already available in your workspace.- Select the non-US revenue for all movies (the entire second column of
all_wars_matrix), store the result asnon_us_all. - Use
mean()onnon_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 asnon_us_some. - Use
mean()again to print out the average of the values innon_us_some.
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_matrix multiplies each element of my_matrix by
two.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.- Divide(除以)
all_wars_matrixby 5, giving you the number of visitors in millions. Assign the resulting matrix tovisitors. - Print out
visitorsso you can have a look.
A little arithmetic with matrices (2)
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).
%*% in
R.- Divide
all_wars_matrixbyticket_prices_matrixto get the estimated(估计) number of US and non-US visitors for the six movies. Assign the result tovisitors. - From the
visitorsmatrix, select the entire first column, representing (描述)the number of visitors in the US. Store this selection asus_visitors. - Calculate the average number of US visitors; print out the result.
浙公网安备 33010602011771号