R语言数据结构2—matrix
来源:互联网 发布:二十四孝知乎 编辑:程序博客网 时间:2024/06/05 16:51
矩阵
矩阵是一个二维数组,只是每个元素都拥有相同的模式(数值型、字符型或逻辑型)。可通
过函数matrix创建矩阵。一般使用为:
matrix(vector = , nrow = , ncol = , byrow = ,dimnames = list(,))
其中vector包含了矩阵的元素,nrow和ncol用以指定行和列的维数,dimnames包含了可选的、
以字符型向量表示的行名和列名。选项byrow则表明矩阵应当按行填充(byrow=TRUE)还是按
列填充(byrow=FALSE),默认情况下按列填充。
1.Construction of a matrix 构建一个矩阵
my.matrix <- matrix(1:9,byrow=TRUE,nrow=3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
# Box office Star Wars: In Millions (!)
# First element: US
# Second element: Non-US
new.hope <- c(460.998007, 314.4)
empire.strikes <- c(290.475067, 247.9)
return.jedi <- c(309.306177, 165.8)
# Construct matrix(通过vector构建矩阵):
star.wars.matrix <- matrix(c(new.hope, empire.strikes, return.jedi), nrow = 3,
byrow = TRUE)
# give names to rows and columns!
#给矩阵命名
colnames(star.wars.matrix) <- c("US", "non-US")
rownames(star.wars.matrix) <- c("A new hope", "The empire strikes back", "Return of the Jedi")
#打印出矩阵
# Print the matrix to the console:
star.wars.matrix
US non-US
A new hope 460.9980 314.4
The empire strikes back 290.4751 247.9
Return of the Jedi 309.3062 165.8
#计算出row的和
worldwide.vector <- rowSums(star.wars.matrix)
# Print worldwide revenue per movie
worldwide.vector
A new hope The empire strikes back Return of the Jedi
775.4 538.4 475.1
# Bind the new variable total.per.movie as a column to star.wars
#通过连接两个矩阵构建新矩阵
all.wars.matrix <- cbind(star.wars.matrix, worldwide.vector)
all.wars.matirx
US non-US worldwide.vector
A new hope 461.0 314.4 775.4
The empire strikes back 290.5 247.9 538.4
Return of the Jedi 309.3 165.8 475.1
#构建票价矩阵
ticket.prices.matrix <- matrix(c(5, 7, 6, 8, 7, 9), nrow = 3, byrow = TRUE,
dimnames = list(movie.names, col.titles))
visitors <- star.wars.matrix/ticket.prices.matrix
average.us.visitor <- mean(visitors[, 1])
average.non.us.visitor <- mean(visitors[, 2])
visitors
average.us.visitor
average.non.us.visitor
visitors
US non-US
A new hope 92.20000 44.91429
The empire strikes back 48.41667 30.98750
Return of the Jedi 44.18571 18.42222
>average.us.visitor
[1] 61.60079
>average.non.us.visitorverage.non.us.visitor
[1] 31.44134
- R语言数据结构2—matrix
- R语言矩阵(matrix)详解
- R语言中的数据结构——向量
- R语言——高级数据结构
- R语言学习:数据结构2-向量
- R语言数据结构3—array
- R语言数据结构4—dataframe
- R语言数据结构5—factor
- R语言数据结构6—list
- R语言数据结构1—vector
- R语言中数据结构
- R语言中的数据结构
- R语言_数据结构
- R语言的数据结构
- R语言数据结构
- R语言数据结构
- R语言-数据结构
- R语言 数据结构
- linux-virt-install 常用参数一览表
- Oracle 11gOCP 053 v12.02 300--600题部分疑问答案更正
- Count Path Pair
- javascript打开选择对话框/保存对话框
- linux-vnc连接xen虚拟机方法
- R语言数据结构2—matrix
- 面试题:支持O(1)时间内完成pop,push和max的栈
- linux 查看 python 安装路径 适合查看命令的安装路径
- UVa 10878 - Decode the tape 解题报告
- 他山之石____Google Java编程风格指南
- ZOJ-2731
- c语言中的数组和字符串
- win8手机无法安装驱动问题
- uva 10730 - Antiarithmetic?(枚举)