【问题标题】:R summing certain columns in each rowR对每一行中的某些列求和
【发布时间】:2013-07-12 17:39:28
【问题描述】:

我遇到了一个问题,但我确信对于非常熟悉 R 的人来说这非常容易。 我有一个 3008 x 3008 的矩阵。我想要的是对每行中的每 8 列求和。所以基本上你会得到一个现在是 367 x 367 的新矩阵。

这是一个小例子:

           C.1 C.2 C.3 C.4 C.5 C.6
    row1    1   2   1   2   5   6
    row1    1   2   3   4   5   6
    row1    2   6   3   4   5   6
    row1    1   2   3   4   10   6

假设我想对每行中的每 3 列求和,我想最终得到:

           C.1 C.2
    row1    4   13
    row1    6   15
    row1   11   15
    row1    6   20

【问题讨论】:

    标签: r matrix sum aggregate


    【解决方案1】:
    # m is your matrix
    n <- 8
    grp <- seq(1, ncol(m), by=n)
    sapply(grp, function(x) rowSums(m[, x:(x+n-1)]))
    

    如果您是 R 新手,请进行一些解释。grp 是一个数字序列,它给出了每组列的起点:如果您想每 8 列求和,则为 1、9、17 等。

    sapply调用可以理解如下。对于grp 中的每个数字,它调用rowSums 函数,将与该组号对应的矩阵列传递给它。因此,当grp 为 1 时,它会获取第 1-8 列的行总和;当grp 为 9 时,它会获取第 9-16 列的行总和,依此类推。这些是向量,sapply 然后将它们绑定到一个矩阵中。

    【讨论】:

    • 你们太棒了!感谢您及时的回复!这正是我需要的!
    【解决方案2】:

    将矩阵转换为数组,然后使用applyrowSums

    mat <- structure(c(1L, 1L, 2L, 1L, 2L, 2L, 6L, 2L, 1L, 3L, 3L, 3L, 2L, 4L, 4L, 4L, 5L, 5L, 5L, 10L, 6L, 6L, 6L, 6L), 
                     .Dim = c(4L, 6L), 
                     .Dimnames = list(c("row1", "row2", "row3", "row4"), c("C.1", "C.2", "C.3", "C.4", "C.5", "C.6")))
    
    n <- 3 #this needs to be a factor of the number of columns
    a <- array(mat,dim=c(nrow(mat),n,ncol(mat)/n))
    apply(a,3,rowSums)
    #      [,1] [,2]
    # [1,]    4   13
    # [2,]    6   15
    # [3,]   11   15
    # [4,]    6   20
    

    【讨论】:

      【解决方案3】:
      #Create sample data:
      df <- matrix(rexp(200, rate=.1), ncol=20)
      
      #Choose the number of columns you'd like to sum up (e.g., 3 or 8)
      number_of_columns_to_sum <- 3
      
      df2 <- NULL #Set to null so that you can use cbind on the first value below
      for (i in seq(1,ncol(df), by = number_of_columns_to_sum)) {
        df2 <- cbind(df2, rowSums(df[,i:(i+number_of_columns_to_sum-1)]))
      }
      

      【讨论】:

      • 避免在循环中使用cbind(非常慢),这里不需要使用for(副作用)。
      【解决方案4】:

      另一种选择:虽然它可能不那么优雅

      mat <- structure(c(1L, 1L, 2L, 1L, 2L, 2L, 6L, 2L, 1L, 3L, 3L, 3L, 2L, 4L, 4L, 4L, 5L, 5L, 5L, 10L, 6L, 6L, 6L, 6L), 
                       .Dim = c(4L, 6L), 
                       .Dimnames = list(c("row1", "row1", "row1", "row1"), c("C.1", "C.2", "C.3", "C.4", "C.5", "C.6")))
      
      new<- data.frame((mat[,1]+mat[,2]+mat[,3]),(mat[,4]+mat[,5]+mat[,6]))
      names(new)<- c("C.1","C.2")
      new
      

      【讨论】:

      • 对于 3008 x 3008 矩阵来说毫无用处,不是吗?
      猜你喜欢
      • 2012-11-09
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      相关资源
      最近更新 更多