如何在 R 矩阵中按行名查找每列的行和?
要查找按行名计算的每列的行和,我们可以使用 `rowsum` 函数。例如,如果我们有一个名为 M 的矩阵,则可以使用命令 `rowsum(M, row.names(M))` 计算每列带有行名的行和。
示例1
> M1<-matrix(rpois(40,5),nrow=20) > rownames(M1)<-sample(c("Male","Female"),20,replace=TRUE) > colnames(M1)<-c("V1","V2") > M1
输出
V1 V2 Male 3 6 Female 6 5 Female 7 3 Female 2 5 Female 5 3 Female 4 4 Female 1 4 Female 4 4 Female 7 5 Male 2 5 Female 5 5 Male 7 1 Female 5 6 Male 6 5 Female 3 7 Male 5 4 Female 3 6 Male 3 4 Male 4 3 Male 6 2
查找矩阵 M1 的列名对应的行和 -
> rowsum(M1,row.names(M1))
输出
V1 V2 Female 52 57 Male 36 30
示例2
> M2<-matrix(rpois(40,10),nrow=20) > rownames(M2)<-sample(LETTERS[1:4],20,replace=TRUE) > colnames(M2)<-c("X1","X2") > M2
输出
X1 X2 B 6 9 D 12 14 C 8 9 A 9 8 A 6 13 A 10 8 D 7 12 B 9 6 A 11 11 C 6 15 D 12 6 B 5 9 C 12 11 A 12 6 B 10 9 D 15 14 C 8 10 B 11 9 A 8 8 B 19 4
查找矩阵 M2 的列名对应的行和 -
> rowsum(M2,row.names(M2))
输出
X1 X2 A 56 54 B 60 46 C 34 45 D 46 46
示例3
> M3<-matrix(sample(0:9,40,replace=TRUE),nrow=20) > rownames(M3)<-sample(c("Hot","Cold"),20,replace=TRUE) > colnames(M3)<-c("C1","C2") > M3
输出
C1 C2 Cold 1 5 Hot 1 3 Hot 4 5 Cold 0 3 Hot 2 8 Hot 7 6 Hot 5 9 Cold 5 9 Cold 9 9 Cold 8 7 Cold 9 2 Cold 0 6 Cold 0 3 Cold 6 3 Cold 3 8 Cold 6 2 Cold 5 0 Cold 4 9 Cold 9 2 Hot 6 5
查找矩阵 M3 的列名对应的行和 -
> rowsum(M3,row.names(M3))
输出
C1 C2 Cold 65 68 Hot 25 36
广告