I want to take the weighted mean of a group using the aggregate function in r.
Here is what my data looks like:
set.seed(1980)
Group_1 <- sample(letters[1:4], 50, TRUE)
Group_2 <- sample(letters[8:13], 50, TRUE)
Weight <- sample(seq(1,50), 50, TRUE)
Value <- sample(seq(1,50), 50, TRUE)
DF <- data.frame(Group_1, Group_2, Weight, Value)
head(DF)
I want to take the weighted mean of the Value column, using the Weight column, for each pairwise group.
Such that, the aggregate function would look like:
aggregate(Value ~ Group_1 + Group_2, data = df, mean)
How would I take the weighted mean using the aggregate function?
Instead of
mean, useweighted.mean. However,aggregate, may not be an option here becauseaggregateloop over only the 'Value' column and it doesn't have access to the 'Weight' for each group-output
If we want to use
base R, thenbyshould work