0

I have a data-frame like this

no        date          charges
050034    2011-07-14    3312.00
000859    2012-07-13    10913.54
05266     2013-07-16    159.00
000859    2012-07-13    370.00 
000859    2014-07-16    21881.36
38027     2012-07-13    164.00

I want to find average total charges group by each no and date in unique date. I used

summary<-df %>% group_by(no) %>% summarize_each(funs(total_charges=sum(charges)))

to get result like this:

no        date          charges
050034    2011-07-14    3312.00
000859    2012-07-13    11283.54
05266     2013-07-16    159.00
000859    2014-07-16    21881.36
38027     2012-07-13    164.00

(we only have one no=000859 at 2012-07-13) but my code does not work correctly!

EDIT:::::: How could I find average of total charges per month for each no?

Sajjad
  • 67
  • 2
  • 8
  • @Procrastinatus Maximus I did not find any similar question before posting my question! – Sajjad Jul 08 '16 at 17:25
  • no problem, hope your problem is solved now – Jaap Jul 08 '16 at 17:27
  • I edited my question to be more specified – Sajjad Jul 08 '16 at 18:46
  • The question should stay closer imo as it is explained in the duplicate-target. You have to use both `no` and `month` as grouping variables. You can create the `month` variable with for example `lubridate::month(date)`. – Jaap Jul 09 '16 at 17:17

2 Answers2

0

Assuming that your data frame is called df you can use:

aggregate(charges ~ no + date, data=df, sum)
Jacob F
  • 366
  • 1
  • 6
0

You can group by more than one variable:

df%>%group_by(date,no)%>%summarise(total_charges=sum(charges))

biomiha
  • 1,358
  • 2
  • 12
  • 25
  • how could I find total charges average per no in each month? – Sajjad Jul 08 '16 at 18:48
  • @Sajjad your question asked for total, so this answer used `sum`. The R function for calculating averages is `mean()`, so if you want the average instead of the total you should use `mean()` instead of `sum()`. You may look at some of the introductory resources [in the R tag wiki](http://stackoverflow.com/tags/r/info). – Gregor Thomas Jul 08 '16 at 18:58