我正在使用矩阵和命令rowSums和rowMeans,colSums和colMeans。我有大部分工作,直到我想取rowSums的总和,colSums的总和,rowMeans的平均值,colMeans的平均值。请参阅下面的最后一行代码。 rbind(matRow,colSums,colMeans)。你能协助纠正矩阵垫中较低的2x2矩阵吗?诸如rowSums [colSums]之类的命令产生错误。
mydata=read.table("mydata.txt")
mydata
V1 V2 V3 V4
1 1 2 4 7
2 2 4 6 8
mat=as.matrix(mydata)
mat
V1 V2 V3 V4
[1,] 1 2 4 7
[2,] 2 4 6 8
rownames(mat) <- c("r1", "r2")
colnames(mat) <- c("c1","c2","c3","c4")
mat
c1 c2 c3 c4
r1 1 2 4 7
r2 2 4 6 8
dim(mat)
[1] 2 4
rowSums=rowSums(mat)
colSums=colSums(mat)
rowMeans=rowMeans(mat)
colMeans=colMeans(mat)
matRow=cbind(mat,rowSums,rowMeans)
matRow
c1 c2 c3 c4 rowSums rowMeans
r1 1 2 4 7 14 3.5
r2 2 4 6 8 20 5.0
#Append colSums and colMeans below matRow
#far lower R corner 2x2 is not correct
#see final computation
matCol=rbind(matRow,colSums,colMeans)
Warning message:
In rbind(matRow, colSums, colMeans) :
number of columns of result is not a multiple of vector length (arg 2)
matCol
c1 c2 c3 c4 rowSums rowMeans
r1 1.0 2 4 7.0 14.0 3.5
r2 2.0 4 6 8.0 20.0 5.0
colSums 3.0 6 10 15.0 3.0 6.0
colMeans 1.5 3 5 7.5 1.5 3.0
答案 0 :(得分:2)
创建数据:
mat <- matrix(c(1, 2, 2, 4, 4, 6, 7, 8),
nrow = 2,
dimnames = list(c("r1", "r2"),
c("c1","c2","c3","c4")))
首先进行行摘要
m2 <- cbind(mat, rowSums(mat), rowMeans(mat))
现在m2
的形状与mat
不同,它还有两列。这样做你可以得到摘要而不是NA
的摘要列,但并非所有这些都有意义(比如行的总和意味着..)
rbind(m2, colSums(m2), colMeans(m2))
在您的示例中,您计算了原始矩阵的摘要,因此您有两行和四列,但matRow
有6列,与colSums
(4列)不匹配。
答案 1 :(得分:1)
> rbind(1:5, 1)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 1 1 1 1
有时这非常有用,有时这很愚蠢。我不确定你认为底角应该包含什么,但是在这里你可以找到缺少值的方法。
rbind(matRow, c(colSums, NA, NA), c(colMeans, NA, NA))
c1 c2 c3 c4 rowSums rowMeans
r1 1.0 2 4 7.0 14.0 3.5
r2 2.0 4 6 8.0 20.0 5.0
colSums 3.0 6 10 15.0 NA NA
colMeans 1.5 3 5 7.5 NA NA