N个连续列的Rowmeans

时间:2017-11-15 14:57:26

标签: r dataframe

在包含n*3列的数据框中,如何计算R中每三个(或任何其他数量)连续列的行均值,例如列(1,2,3)(4,5,6),{{ 1}}等等?

有一个解决方案here,但我想知道它是否会更优雅。

3 个答案:

答案 0 :(得分:2)

Base 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)]))

答案 1 :(得分: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

答案 2 :(得分:0)

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

  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-09-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
)
相关问题