如何在R中按两列分组 [英] How to group by two columns in R

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

问题描述

我有一个数据框,我试图对其进行分组,然后根据两列进行求和.两列是字符,一个是月份,另一个是变量.

I have a data frame that I am trying to group and then sum based on two columns. The two columns are characters with one being month and the other variable.

以下是数据框架和结构的示例.

The following is a sample of the data frame and structure.

#row.names   month    variable   amount
  1          1-Jan       x        1000
  2          1-Jan       x        3000
  3          2-Feb       z        5000
  4          2-Feb       y        3000 

我尝试先对数据进行分组,然后尝试进行汇总,但是我无法让group_by_()完成此操作.下面是我尝试的代码.

I tried to group the data first and then I was going to try to summarise, however I am unable to get group_by_() to do the trick. Below is the code I tried.

byVarMonth <- group_by_(df, variable, (as.date(month)))

感谢您的帮助.

推荐答案

您显然对将角色[month]用作Date变量不感兴趣.考虑到我没错,您可以执行以下操作:

You apparently are not interested in taking your Character [month] as a Date variable. Considering that I'm not wrong you could simply do something like this:

library(dplyr)

tab %>%
  group_by(month, variable) %>%
  summarise(a_sum=sum(amount),
            a_mean=(mean(amount)))

并得到这个:

Source: local data frame [3 x 4]
Groups: month

  month variable a_sum a_mean
1 1-Jan        x  4000   2000
2 2-Feb        y  3000   3000
3 2-Feb        z  5000   5000

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

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