如何按R中的分组列求和? [英] How to sum by grouped columns in R?

查看:604
本文介绍了如何按R中的分组列求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的输入。具有n列的数据框,以及将每个ID分配给组的辅助数据框。

This is my input. A dataframe with n columns, and an auxiliary dataframe that assigns each id to a group.

df <- data.frame(
  a1 = c(1,2,3), 
  a2 = c(2,3,4), 
  b1 = c(4,5,6), 
  b2 = c(5,6,7)
)
aux <- data.frame(
  id = c("a1", "a2", "b1", "b2"),
  group = c("a", "a", "b", "b")
)

获得此输出的通用方法是什么? (求和a1 + a2和b1 + b2)

What's a generalizable way to get to this output? (summing a1 + a2, and b1 + b2)

desired_output <- data.frame(
  a = c(3,5,7),
  b = c(9,11,13)
)

我尝试使用 dplyr :: group_by tidyr :: unite ,但是我没有

I've tried using dplyr::group_by and tidyr::unite, but I haven't gotten it to work yet.

推荐答案

为了避免拆分数据帧并通过代码传递较长的数据帧列表,您可以使用以下索引:

In order to avoid having to split data frames and pass long lists of data frames through your code, you can just work with the indices:

cols <- split(aux$id, aux$group)

data.frame(lapply(cols, function(i) rowSums(df[i])))

这篇关于如何按R中的分组列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆