R语言从基础入门到提高(四)matrices(矩阵)
来源:互联网 发布:淘宝上专卖点怎么申请 编辑:程序博客网 时间:2024/06/04 23:01
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)
matrix()
function:(三个参数说明)- The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we use
1:9
which is a shortcut(快捷方式) forc(1, 2, 3, 4, 5, 6, 7, 8, 9)
. - The argument
byrow
indicates(表明) 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
nrow
indicates 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 = 3
andbyrow = 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_vectorcolnames(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_matrix
with theregion
vector. - Use
rownames()
to name the rows ofstar_wars_matrix
with thetitles
vector. - Print out
star_wars_matrix
to 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_matrix
and 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_matrix
that 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(故事)
cbind()
has a rbind()
, every colSums()
has a rowSums()
. Your R workspace already contains the all_wars_matrix
that you constructed in the previous exercise; type all_wars_matrix
to have another look. Let's now calculate 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_vector
to 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_all
to 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_matrix
by 5, giving you the number of visitors in millions. Assign the resulting matrix tovisitors
. - Print out
visitors
so 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_matrix
byticket_prices_matrix
to get the estimated(估计) number of US and non-US visitors for the six movies. Assign the result tovisitors
. - From the
visitors
matrix, 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.
- R语言从基础入门到提高(四)matrices(矩阵)
- R语言从基础入门到提高(一)Intro to basics(基础介绍)
- R语言从基础入门到提高(二)Vectors(向量)
- R语言从基础入门到提高(三)Vectors(向量)
- R语言从基础入门到提高(五)factor 因子
- R语言从基础入门到提高(六) frame 框架
- R语言从基础入门到提高(七)LIST (列表)
- R语言入门基础:矩阵
- Maven从入门到提高(四)
- C语言从入门到精通(基础)
- matlab从入门到精通(二)matlab语言基础
- R语言基础入门(全)
- 对称矩阵(Symmetric Matrices)
- 对称矩阵(Symmetric Matrices)
- mybatis 从入门到精通(四)
- JavaScript从入门到放弃(四)
- learning R with swirl- Matrices and Data Frames(矩阵和数据帧)
- R语言基础入门
- angularjs设置focus
- 初识kafka
- php上传2M以上文件限制问题
- socket :sockaddr_in 赋值
- zepto与jquery使用区别总结
- R语言从基础入门到提高(四)matrices(矩阵)
- 自定义标签的使用
- 怎么实现用java远程访问oracle数据库?
- js定时和离开当前页面事件
- 面试-机试-编程题--剑指offer
- 变态暴力家庭过河问题
- 浏览器事件
- mongoDB常用命令
- linux常用命令