【问题标题】:Rowmeans for N sequential columnsN 个连续列的 Rowmeans
【发布时间】:2018-04-28 20:47:33
【问题描述】:

在具有n*3 列的数据框中,如何计算每三个(或任何其他数量)连续列的行均值,例如对于(1,2,3)(4,5,6)(7,8,9) 等列?

有解决办法here on Code Review-Mean of many subsets of a dataframe,不过不知道有没有更优雅的方法。

【问题讨论】:

  • t(rowsum(t(dat), as.integer(gl(ncol(dat), 3, ncol(dat)))))/3
  • sapply(split.default(dat, rep(seq_along(dat), each=3, length.out=ncol(dat))), rowMeans)

标签: r dataframe


【解决方案1】:

基础 R 解决方案(指定应用函数并遍历这些组的列数):

# Generate dummy data (matrix 2 x 9)
foo <- matrix(rnorm(18), 2)
# By how many columns apply function
BY <- 3
# Apply rowmeans by rows and columns
sapply(1:(ncol(foo)/BY), function(x) rowMeans(foo[, ((x * BY) - BY + 1):(x * BY)]))

【讨论】:

    【解决方案2】:

    您可以使用以下内容。此示例基于链接问题中提供的数据集以及每两个连续列。

    dat <- data.frame(a1 = 9:11, a2 = 2:4, b1 = 3:5,
                  b2 = 4:6, c1 = 5:7, c2 = 1:3)
    
    n <- 2
    t(rowsum(t(dat), as.integer(gl(ncol(dat), n, ncol(dat))))) / n
    
    ##        1   2 3
    ## [1,] 5.5 3.5 3
    ## [2,] 6.5 4.5 4
    ## [3,] 7.5 5.5 5
    

    【讨论】:

    • @Hrant 它产生因子。阅读它?gl
    【解决方案3】:

    这是一种没有循环的方法。

    1. 矩阵转换为数组。
    2. 数组转置为aperm() 以允许...
    3. colMeans() 返回预期的输出。 colMeans() 处理维度的方式与 rowMeans() 不同,转置提供了预期的输出。
    df<-matrix(1:30, nrow = 3, ncol = 6)
    
    ncols <- 2
    
    colMeans(
      aperm(
        array(df, dim = c(3, ncols, ncol(df) / ncols)),
        perm = c(2,1,3)
        )
      )
    #>      [,1] [,2] [,3]
    #> [1,]  2.5  8.5 14.5
    #> [2,]  3.5  9.5 15.5
    #> [3,]  4.5 10.5 16.5
    

    reprex package (v0.3.0) 于 2019 年 9 月 30 日创建

    这是三种方法中最快的:

    # A tibble: 3 x 13
      expression       min median `itr/sec` mem_alloc
      <bch:expr>    <bch:> <bch:>     <dbl> <bch:byt>
    1 aperm_method  33.4us 35.1us    27291.        0B
    2 rowsum_method 55.6us 57.8us    16854.        0B
    3 sapply_method 93.8us 96.9us    10210.    46.5KB
    

    原始代码:

    bench::mark(
      aperm_method = {
        ncols <- 2
        colMeans(
          aperm(
            array(df, dim = c(nrow(df), ncols, ncol(df) / ncols)),
            perm = c(2,1,3)
          )
        )
      }
      ,
      rowsum_method = {
        n <- 2; 
        t(rowsum(t(df), as.integer(gl(ncol(df), n, ncol(df))))) / n
      }
      , 
      sapply_method = {
        BY = 2
        sapply(1:(ncol(df)/BY), function(x) rowMeans(df[, ((x * BY) - BY + 1):(x * BY)]))
      }
      ,
      check = F #all the same except rowsum_method has colnames
    )
    

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多