Re: [R] Calculating sum of squares from density estimates

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Thu, 24 Jan 2008 15:24:11 +0000 (UTC)

Rainer M Krug <r.m.krug_at_gmail.com> wrote in news:4798991D.3000607_at_gmail.com:

> Hi
>
> I have some density estimates obtained from density(). I would like
> to calculate the sum of squares of these. As the x values of the
> estimates are not the same, and I would prefer not to restrict the
> estiomate to a certain range of x values, how can I do the
> calculation?
>
> Lets say:
>
> d1 <- density(Data1)
> d2 <- density(Data2)
>
> If the x values would be the same, I would:
>
> ssq <- sum( (d1$y - d2$y)^2 )
>
> but as it isn't, I can't do that.
>
> is there an easy way to get the sum of squares?

Presumably there is a common domain for these densities. Consider forcing the x values to be the same by identically specifying n=, from=, and to=?

> ?density
> x <- rnorm(200,1,1)
> x2 <- rnorm(200,1,1)
> d1 <- density(x, n=512, from=-1, to= 4)
> d2 <- density(x2, n=512, from=-1, to= 4)
> ssq <- sum( (d1$y - d2$y)^2 )
> ssq
[1] 0.4722924

> x <- rnorm(200,1,1)
> x2 <- rnorm(200,1.5,1)
> d1 <- density(x, n=512, from=-1, to= 4)
> d2 <- density(x2, n=512, from=-1, to= 4)
> ssq <- sum( (d1$y - d2$y)^2 )
> ssq
[1] 2.111498

-- 
David Winsemius

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 24 Jan 2008 - 15:33:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 25 Jan 2008 - 08:30:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive