[R] Need to compute density as done by panel.histogram

Peter Ehlers ehlers at ucalgary.ca
Wed Aug 3 12:57:26 CEST 2011


On 2011-08-02 11:51, Sébastien Bihorel wrote:
> Hi,
>
> This might be a simple problem but I don't know how to calculate a random
> variable density the way panel.histogram does it before it creates the
> actual density rectangles. The documentation says that it uses the density
> function but the actual code suggests that the hist.constructor function
> (which does not seem to be easily accessible).

The documentation in ?histogram is misleading. I think that the intent
is that density() is used in panel.densityplot but panel.histogram uses
hist(), as is clear in ?panel.histogram.

So you'll find the code for the density rectangles in hist.default
where 'counts' is computed and followed with

  dens <- counts/(n * diff(breaks))

You might find the code for truehist() in the MASS package easy to
follow.

To see how hist.constructor calls hist():

  lattice:::hist.constructor

Peter Ehlers

>
> Any suggestion for computing the density values of foo$x in the following
> example will be welcome.
>
>
> require(lattice)
> set.seed(12345)
>
> foo1<-
> data.frame(x=rnorm(100,0,0.1),grp=1,by=rep(1:2,each=50),by2=rep(1:2,times=50))
> foo2<-
> data.frame(x=rnorm(100,2,1),grp=2,by=rep(1:2,each=50),by2=rep(1:2,times=50))
> foo<- rbind(foo1,foo2)
>
> xplot<- histogram(~x,data=foo, type='density')
>
>
> PS: the present question relates to a workaround for another problem
> previously submitted to the list (
> https://stat.ethz.ch/pipermail/r-help/attachments/20110727/5f0a8853/attachment.pl).
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



More information about the R-help mailing list