在r中平均每16列

时间:2012-05-22 14:42:52

标签: r

  

可能重复:
  apply a function over groups of columns

我有一个data.frame有30行和多列(1000+),但我需要将每16列平均放在一起。例如,数据框将如下所示(我将其截断以使其更容易......):

Col1            Col2            Col3            Col4........

4.176           4.505           4.048           4.489
6.167           6.184           6.359           6.444
5.829           5.739           5.961           5.764
.
.
.

因此,我无法聚合(我没有列表),我试过:

a <- data.frame(rowMeans(my.df[,1:length(my.df)]) )

这给了我所有1000多个coumns的平均值,但有没有办法说我想每16列直到最后? (它们是列总数的16的倍数)。

次要的,不太重要的一点,但也有助于解决这个问题。 列名称采用以下结构:

XXYY4ZZZ.txt

平均所有我需要的列是一个只有XXYY的新列名,其余的将被平均掉。我知道我可以使用gsub但是有一种最佳的方法可以一次性进行平均和这个操作吗?

我仍然是R的新手,因此我不知道在哪里以及如何找到答案。

2 个答案:

答案 0 :(得分:5)

这是一个改编自@ ben的问题和@ TylerRinker来自apply a function over groups of columns的答案的例子。它应该能够按列的间隔在矩阵或数据帧上应用任何函数。

# Create sample data for reproducible example
n <- 1000
set.seed(1234)
x <- matrix(runif(30 * n), ncol = n)

# Function to apply 'fun' to object 'x' over every 'by' columns
# Alternatively, 'by' may be a vector of groups
byapply <- function(x, by, fun, ...)
{
    # Create index list
    if (length(by) == 1)
    {
        nc <- ncol(x)
        split.index <- rep(1:ceiling(nc / by), each = by, length.out = nc)
    } else # 'by' is a vector of groups
    {
        nc <- length(by)
        split.index <- by
    }
    index.list <- split(seq(from = 1, to = nc), split.index)

    # Pass index list to fun using sapply() and return object
    sapply(index.list, function(i)
            {
                do.call(fun, list(x[, i], ...))
            })
}

# Run function
y <- byapply(x, 16, rowMeans)

# Test to make sure it returns expected result
y.test <- rowMeans(x[, 17:32])
all.equal(y[, 2], y.test)
# TRUE

你可以用它做其他奇怪的事情。例如,如果您需要知道每10列的总和,请务必删除NA s(如果存在):

y.sums <- byapply(x, 10, sum, na.rm = T)
y.sums[1]
# 146.7756 
sum(x[, 1:10], na.rm = T)
# 146.7756 

或找到标准偏差:

byapply(x, 10, apply, 1, sd)

<强>更新

by也可以指定为组的向量:

byapply(x, rep(1:10, each = 10), rowMeans)

答案 1 :(得分:0)

这对我来说适用于更小的数据框:

rowMeans(my.df[,seq(1,length(my.df),by=16)])
相关问题