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)

#print

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


0 0
原创粉丝点击