admin 管理员组文章数量: 1086019
2024年4月16日发(作者:in的前缀用法及意义)
矩阵
矩阵是一个二维数组,只是每个元素都拥有相同的模式(数值型、字符型或逻辑型)。可通
过函数matrix创建矩阵。一般使用格式为:
其中vector包含了矩阵的元素,nrow和ncol用以指定行和列的维数,dimnames包含了可选的、
以字符型向量表示的行名和列名。选项byrow则表明矩阵应当按行填充(byrow=TRUE)还是按
列填充(byrow=FALSE),默认情况下按列填充。
uction of a matrix 构建一个矩阵
<- matrix(1:9,byrow=TRUE,nrow=3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
2.
# Box office Star Wars: In Millions (!)
# First element: US
# Second element: Non-US
<- c(460.998007, 314.4)
s <- c(290.475067, 247.9)
<- c(309.306177, 165.8)
# Construct matrix(通过vector构建矩阵):
<- matrix(c(, s, ), nrow = 3,
byrow = TRUE)
# give names to rows and columns!
#给矩阵命名
colnames() <- c("US", "non-US")
rownames() <- c("A new hope", "The empire strikes back", "Return of the Jedi")
#打印出矩阵
# Print the matrix to the console:
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的和
<- rowSums()
# Print worldwide revenue per movie
A new hope The empire strikes back Return of the Jedi
775.4 538.4 475.1
# Bind the new variable as a column to
#通过连接两个矩阵构建新矩阵
<- cbind(, )
US non-US
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
#构建票价矩阵
<- matrix(c(5, 7, 6, 8, 7, 9), nrow = 3, byrow = TRUE,
dimnames = list(, ))
visitors <- /
r <- mean(visitors[, 1])
r <- mean(visitors[, 2])
visitors
r
r
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
>r
[1] 61.60079
>r
版权声明:本文标题:R语言-矩阵 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1713236780a625331.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论