[R] confidence bounds using contour plot

Pascal Hänggi pascal.haenggi at hydrologie.unibe.ch
Fri Jun 27 10:51:45 CEST 2008


Sorry for the wrong placing of my last email.
Here a solution to my problem and incomprehension respectively:


# Example 95%
x <- rnorm(1000, mean = 0, sd = 1)
y <- rnorm(1000, mean = 1, sd = 1.3)
kerneld <- kde2d(x, y, n = 100, lims = c(-5.0, 5.0, -5.0, 5.0))

pp <- array()
for (i in 1:1000){
	z.x <- max(which(kerneld$x < x[i]))
	z.y <- max(which(kerneld$y < y[i]))
	pp[i] <- kerneld$z[z.x, z.y]
}

confidencebound <- quantile(pp, 0.05, na.rm = TRUE)

plot(x, y, pch = 19, cex = 0.5)
contour(kerneld, levels = confidencebound, col = "red", add = TRUE)


# Test
test <- array()
kerneld.xy <- contourLines(kerneld, levels = confidencebound)
for (i in 1:1000) {
test[i] <- inside(list(x = x[i], y = y[i]),
                  list(x = kerneld.xy[[1]]$x, y = kerneld.xy[[1]]$y))
}
sum(test)/1000


--
  Pascal Hänggi
 
  Universität Bern
  Geographisches Institut, Gruppe für Hydrologie
  Hallerstrasse 12
  CH-3012 Bern
 
  +41 (0)31 631 54 71
  pascal.haenggi at hydrologie.unibe.ch
  http://www.hydrologie.unibe.ch
--

-----Ursprüngliche Nachricht-----
Von: Pascal Hänggi [mailto:pascal.haenggi at hydrologie.unibe.ch] 
Gesendet: Mittwoch, 25. Juni 2008 17:38
An: 'r-help at r-project.org'
Betreff: confidence bounds using contour plot

Hello

I'm trying to calculate 2d confindence bounds into a scatterplot using the
function "kde2d" (package MASS) and a contour plot.

I found a similar post providing a solution - unfortunatly I do not realy
understand which data I have to use to calculated the named "quantile":

Post URL: http://tolstoy.newcastle.edu.au/R/help/03b/5384.html

> (...)
>
>> Is there a way to plot a contour (empirical?) containing, say, 95% of the
>> values. 
>
>Yes. You need a 2D density estimate (e.g. kde2d in MASS) then compute the
>density values at the points and draw the contour of the density which
>includes 95% of the points (at a level computed from the sorted values via
>quantile()).
>
>-- 
>Brian D. Ripley
>(...)

--
Example:

x <- rnorm(1000, mean = 0, sd = 1)
y <- rnorm(1000, mean = 1, sd = 1.3)
kerneld <- kde2d(x, y, n = 200, lims = c(-1.0, 1.0, 0.0, 2.0))

confidencebound <- quantile(kerneld$z, probs= 0.95)

plot(x, y, pch=19, cex=0.5)
contour(kerneld, levels = confidencebound, col="red", add = TRUE)
--

How can I calculate the right contour containing 95% of the values?

Thank's for your help.
Pascal

R 2.7.0, Win XP

 
--
  Pascal Hänggi
 
  Universität Bern
  Geographisches Institut, Gruppe für Hydrologie
  Hallerstrasse 12
  CH-3012 Bern
 
  +41 (0)31 631 54 71
  pascal.haenggi at hydrologie.unibe.ch
  http://www.hydrologie.unibe.ch
--



More information about the R-help mailing list