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(, )

#print

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


本文标签: 矩阵 构建 前缀 维数 字符