gpt4 book ai didi

r - 在 r 中平均每 16 列

转载 作者:行者123 更新时间:2023-12-04 12:23:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
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 多个 couns 的平均值,但是有没有办法说我想每 16 列执行一次直到最后? (它们是总列数的 16 的倍数)。

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

一旦平均列,我需要的只是一个新的列名,只有 XXYY因为其余的将被平均。我知道我可以使用 gsub 但是有没有一种最佳方法可以一次性完成平均和这个操作?

我对 R 还是比较陌生,因此我不确定在哪里以及如何找到答案。

最佳答案

这是一个改编自@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)

关于r - 在 r 中平均每 16 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com