Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by two columns in R

Tags:

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  

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))) 

Thanks for the help.

like image 806
Clayton Samples Avatar asked Oct 15 '15 15:10

Clayton Samples


1 Answers

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))) 

and get this:

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 
like image 57
Paulo E. Cardoso Avatar answered Sep 20 '22 19:09

Paulo E. Cardoso