【发布时间】:2016-05-27 22:32:27
【问题描述】:
我正在使用矩阵和命令 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
在R中将表格转换为矩阵
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)
将 rowSums 追加到 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
【问题讨论】:
-
以不同于生成它们的函数的方式命名您的摘要。只有在
cbind之后才调用列汇总函数 -
我得到了同样的结果?你能解释一下你会cbind吗?最后我是行绑定的。
标签: r