2018-10-31
閱讀量:
1050
R語(yǔ)言使用技巧--與矩陣、數(shù)據(jù)框相關(guān)的處理函數(shù)
使用用 rowSums()
函數(shù)可以加載行資料,而 colSums()
函數(shù)可以加載列資料。
> set.seed(123) > ice_cream <- matrix(round(runif(15) * 100), nrow = 5)
> colnames(ice_cream) <- c("Vanilla", "Chocolate", "Strawberry")
> rownames(ice_cream) <- c("Mon", "Tue", "Wed", "Thu", "Fri")
> ice_cream Vanilla Chocolate Strawberry Mon
29 5 96 Tue 79 53 45 Wed 41 89 68 Thu 88 55 57 Fri 94 46 10
我們可以利用 rowSums()
計(jì)算每天總共賣出多少冰淇淋,也可以利用 colSums()
計(jì)算每種口味的總銷量為何。
> set.seed(123)
> ice_cream <- matrix(round(runif(15) * 100), nrow = 5)
> colnames(ice_cream) <- c("Vanilla", "Chocolate", "Strawberry")
> rownames(ice_cream) <- c("Mon", "Tue", "Wed", "Thu", "Fri")
> rowSums(ice_cream)
Mon Tue Wed Thu Fri 130 177 198 200 150
> colSums(ice_cream)
Vanilla Chocolate Strawberry 331 248 276
我們亦可以利用 cbind()
將列加載的結(jié)果加入原本的資料中。
> set.seed(123)
> ice_cream <- matrix(round(runif(15) * 100), nrow = 5)
> colnames(ice_cream) <- c("Vanilla", "Chocolate", "Strawberry")
> rownames(ice_cream) <- c("Mon", "Tue", "Wed", "Thu", "Fri")
> ice_cream <- cbind(ice_cream, Totals = rowSums(ice_cream))
> ice_cream
Vanilla Chocolate Strawberry Totals Mon
29 5 96 130 Tue 79 53 45 177 Wed 41 89 68 198 Thu 88 55 57 200 Fri 94 46 10 150
利用 rbind()
將加載的結(jié)果也加入。
> set.seed(123) > ice_cream <- matrix(round(runif(15) * 100), nrow = 5)
> colnames(ice_cream) <- c("Vanilla", "Chocolate", "Strawberry")
> rownames(ice_cream) <- c("Mon", "Tue", "Wed", "Thu", "Fri")
> ice_cream <- cbind(ice_cream, Totals = rowSums(ice_cream))
> ice_cream <- rbind(ice_cream, Totals = colSums(ice_cream))
> ice_cream Vanilla Chocolate Strawberry Totals Mon
29 5 96 130 Tue 79 53 45 177 Wed 41 89 68 198 Thu 88 55 57 200 Fri 94 46 10 150 Totals 331 248 276 855






評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論