r - 计算数据框中每 13 行的平均值

标签 r dataframe split

我有一个包含 2 列和 3659 行的数据框 df
我试图通过在此数据框中每 10 或 13 行求平均值来减少数据集,因此我尝试了以下操作:

# number of rows per group
n=13
# number of groups
n_grp=nrow(df)/n
round(n_grp,0)
# row indices (one vector per group)
idx_grp <- split(seq(df), rep(seq(n_grp), each = n))

# calculate the col means for all groups
res <- lapply(idx_grp, function(i) {
  # subset of the data frame
  tmp <- dat[i]
  # calculate row means
  colMeans(tmp, na.rm = TRUE)
})
# transform list into a data frame
dat2 <- as.data.frame(res)

但是,我不能将行数除以 10 或 13,因为数据长度不是拆分变量的倍数。所以我不确定应该怎么做(我只想计算最后一组的平均值 - 即使少于 10 个元素)

我也试过这个,但结果是一样的:
df1=split(df, sample(rep(1:301, 10)))

最佳答案

这是使用 aggregate() 的解决方案和 rep() .

df <- data.frame(a=1:12, b=13:24 );
df;
##     a  b
## 1   1 13
## 2   2 14
## 3   3 15
## 4   4 16
## 5   5 17
## 6   6 18
## 7   7 19
## 8   8 20
## 9   9 21
## 10 10 22
## 11 11 23
## 12 12 24
n <- 5;
aggregate(df, list(rep(1:(nrow(df) %/% n + 1), each = n, len = nrow(df))), mean)[-1];
##      a    b
## 1  3.0 15.0
## 2  8.0 20.0
## 3 11.5 23.5
此解决方案的重要部分是处理 nrow(df) 的不可分性问题。来自 n正在指定 len length.out 的参数(实际上完整的参数名称是 rep() ) ,它会自动将组向量限制为适当的长度。

关于r - 计算数据框中每 13 行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359427/

相关文章:

r - 如何在R中的分组条形图中生成堆叠条形图

objective-c - 使用 RCocoa 在 R 中加载 objective-c 库

r - 使用R分割大型.wav文件的快速方法

python - 基于过滤器和多列索引的新列?

r - 给定数字和 n 组,如何将数字随机分成多个数字?

Java - 将 List<String> 拆分为...子列表?

r - 与 lmerTest 一起使用时,anova() 不显示 p 值

r - 如何折叠频率表的行以将其计数添加到新列中?

c# - 在 C# 中将字符串拆分为两个字符

r - 在R中,如何将data.frame的聚合转换为data.table的聚合?