I have a dataset like this:
data.frame(car brand, car model, car sold, co2 emission)
And I want to get the total nb sold per car brand. So I did this:
x <- aggregate(carsold ~ carbrand, data=data.frame, FUN=sum)
Then, I want to get the average co2 emission per car brand.
y <- aggregate(co2emission ~ carbrand, data=data.frame, FUN=mean)
And finally I merge x and y
z <- merge(x, y, by="carbrand")
So I get this
data.frame(car brand, nb sold, average co2 emission)
Problem: in the dataset, nb of car sold may be different for each item. So sometimes, for one model I have 3 cars sold with a certain co2 emission, sometimes 1.
How can I aggregate the nb of car sold per car brand with the weighted average of co2 emission ?
Thanks