# Averaging several density functions

I have a data set grouped by a factor (like e.g. cyl in the built in mtcars in R). I plotted the estimated density funtions (desityplot) for each factor using the lattice package, e.g.

library("lattice")
densityplot( ~mtcars$mpg[mtcars$cyl==4] )
densityplot( ~mtcars$mpg[mtcars$cyl==6] )
densityplot( ~mtcars$mpg[mtcars$cyl==8] )


Now I would like to create a densityplot() for the whole dataset but the estimation should disregard the different number of datapoints available for each factor, e.g.

densityplot( ~mtcars\$mpg )


is not what I want, because there are more data points with cyl=8 than data points with cyl=6. Is it possible to estimate the density separately for each factor and than calculate some sort of "average" density? If not, what is the appropriate method for my purpose?

## migrated from stackoverflow.comJul 5 '12 at 15:02

This question came from our site for professional and enthusiast programmers.

• I'm going to go out on a limb and recommend this get migrated to CrossValidated, since in my opinion it needs more attention from the statistical side. – BenBarnes Jul 5 '12 at 12:46
• How do you intend to interpret this average density? – whuber Jul 6 '12 at 22:09
• I found out, that densityplot has a parameter "weights". I think I simply could apply different weight to the diffent classes so that the total sum of the all weights is one. – porst17 Jul 7 '12 at 12:53
• The interpretation is just as follows (using the mtcasrs data set again): Assume that you know that there is the same amount of cars with cyl=4,6,8 in the real world, but you have a different number of samples for each group. Furthermore, you know that you have a representative set of samples. So assigning a appropriate weight to each group should allow to make density estimation for the whole data set. – porst17 Jul 7 '12 at 13:04

I used densityplot( ~ mpg, data=mtcars, weights=myweights ) where myweights contains different weights for the different values in cyl so that the mpg data for cyl=4 has the same influence as the mpg data for cyl=6 etc.