2018-10-31
阅读量:
1013
R语言使用技巧--与矩阵、数据框相关的处理函数
使用用 rowSums()
函数可以加载行资料,而 colSums()
函数可以加载列资料。
> 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()
計算每天總共賣出多少冰淇淋,也可以利用 colSums()
計算每種口味的總銷量為何。
> 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()
将列加载的結果加入原本的資料中。
> 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()
将加载的結果也加入。
> 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






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
1条评论