yso
yso

Reputation: 27

How to find the area under a portion of a histogram?

muhats = replicate(200000,mean(rexp(18, rate = 3))*exp(((-1/2)*mean(rexp(18, rate = 3)))) )
myhist <- hist(muhats)
plot(myhist)

I have the above density function, is there an R command that will give me the area between 2 points under the histogram? I cant seem to find anywhere?

I trying to find a point c on the x axis, such that the area to the left of c is 0.09

Upvotes: 0

Views: 1424

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

You could use this function, which numerically integrates the density using the trapezoidal rule, and returns the first value that exceeds a particular value:

density_area_exceeds <- function(vector, limit)
{
  d <- density(vector)
  d$x[cumsum(diff(d$x) * (d$y[-1] + d$y[-length(d$y)])/2) > limit][1]
}

So you can do:

density_area_exceeds(muhat, 0.09)
#> [1] 0.1961847

So the area of the density to the left of this point on the x axis is 0.09.

Note though, this gives roughly the same answer as just doing:

quantile(g, 0.09)
#>        9% 
#> 0.1971049 

Upvotes: 1

Related Questions