【问题标题】:use of rowMeans, rowSums, colMeans, colSums使用 rowMeans、rowSums、colMeans、colSums
【发布时间】: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


【解决方案1】:

创建数据:

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 不同,它多了两列。这样做你会得到摘要而不是 NAs 也用于摘要列,但并非所有这些都是有意义的(比如行的总和意味着......)

rbind(m2, colSums(m2), colMeans(m2))

在您的示例中,您计算​​了原始矩阵的摘要,因此您有两行四列,但 matRow 有 6 列,与 colSums(4 列)不匹配。

【讨论】:

    【解决方案2】:

    R 经常回收向量;如果它需要更多元素,它将回到开始。在下面的示例中,1 被回收成为长度 5。

    > 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
    

    【讨论】:

    • 谢谢。我正在通过输入答案而不是 4 NA 来修改您的代码。它让我得到了正确的桌子。干杯! MM
    • 没问题!如果有帮助,您介意接受我的回答吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2019-01-17
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多