1. 程式人生 > >R語言資料結構2—matrix

R語言資料結構2—matrix

矩陣

矩陣是一個二維陣列,只是每個元素都擁有相同的模式(數值型、字元型或邏輯型)。可通

過函式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