Reputation: 147
I have a data frame df1:
number=c(4,3,2,3,4,1)
year=c("2000","2000","2000", "2015", "2015", "2015")
items=c(12, 10, 15, 5, 10, 7)
df1=data.frame(number, year, items)
setDT(df1)[, Prop := number/sum(number), by = year]
such that it looks like this:
number year items Prop
1: 4 2000 12 0.4444444
2: 3 2000 10 0.3333333
3: 2 2000 15 0.2222222
4: 3 2015 5 0.3750000
5: 4 2015 10 0.5000000
6: 1 2015 7 0.1250000
I want to get the mean of the number of items per year, so I tried using this fuction:
mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), mean)
but it returns the wrong values for the mean. I want it to return:
Group.1 x
1 2000 2.918918
2 2015 2.296296
where Group.1 is the year and x is the correct mean.
Thanks!
Upvotes: 5
Views: 23174
Reputation: 147
I just had to switch "mean" to "sum" in my aggregate function such that it becomes:
mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), sum)
Upvotes: 2
Reputation: 1800
How about using the dplyr
package
library(dplyr)
df1 %>% group_by(year) %>% summarise(mean = sum(number * items)/sum(items))
which gives
year mean
1 2000 2.918919
2 2015 2.818182
Upvotes: 3
Reputation: 32416
To aggregate
mean number of items/year
aggregate(number ~ year, data=df1, mean)
# year number
# 1 2000 3.000000
# 2 2015 2.666667
For the weighted average in base R you could do standard split-apply-combine
sapply(split(df1, df1$year), function(x) weighted.mean(x$number, w=x$items))
or
sapply(split(df1, df1$year), function(x) sum(x$number*x$items)/sum(x$items))
# 2000 2015
# 2.918919 2.818182
Upvotes: 8