Reputation: 6262
I am a bit lost in how to take average of a data frame formatted in the following way:
id date quantity product
1 12-05-2015 10 apple
2 21-03-2015 12 orange
3 12-05-2015 15 orange
4 21-03-2015 16 apple
Expected result:
date quantity
21-03-2015 14
12-05-2015 12.5
I tried converting it to zoo object, but then I run into issues as dates are non-unique.
Upvotes: 2
Views: 56
Reputation: 887068
Try
aggregate(quantity~date, df1, mean)
# date quantity
#1 12-05-2015 12.5
#2 21-03-2015 14.0
Or
library(data.table)
setDT(df1)[, list(quantity=mean(quantity)), date]
As @Alex A. mentioned in the comments, list(
can be replaced by .(
in the recent data.table versions.
Upvotes: 5
Reputation: 5586
You could also use the dplyr
package. Assuming your data frame is called df
:
library(dplyr)
df %>%
group_by(date) %>%
summarize(quantity = mean(quantity))
# date quantity
# 1 12-05-2015 12.5
# 2 21-03-2015 14.0
This gets the mean quantity grouped by date.
Upvotes: 3