Skip to content
Prev 226504 / 398500 Next

locfit

I got a request from a reputable source (who nonetheless did not copy  
the list, a fact that I only noticed after responding) to post a full  
worked example:

I just tested the bits that I had earlier posted and they seem to fit  
together. The OP was asking for some sort of density conditional on a  
dependent variable which does not really fit with what locfit's author  
used as terminology.

TC.ran <- exp(rnorm(400,1.5,.3))
HDL.ran <- exp(rnorm(400,.4,.3) )

#This is the kde2d version:
require(MASS)
f1<-kde2d(HDL.ran,TC.ran,n=25,lims=c(0,4,2,10))

contour(f1$x,f1$y,f1$z,ylim=c(0,8),xlim=c(0,3),ylab="TC mmol/L",
          xlab="HDL mmol/L")

require(locfit)
# used identical weights although the earlier solution used the  
NHANES3 weights

tc.hdl.fit <-  locfit( ~ HDL.ran+ TC.ran,
                     weights=rep(1, 400),
                     xlim=c(0,0,4,10)
                         )
plot(tc.hdl.fit, ylab="TC mmol/L",
                     xlab="HDL mmol/L")


# if you want an example using the NHANES data, I could do that as well.

Presumably the smoothing parameters could be adjusted to get the kde2d  
and the locfit solutions to be similar.

Density estimates need a formula of the form " ~ x  + y". If a  
regression of a discrete dependent variable is needed then we can  
thrash through that, but it's not really a density as I (or Loader)  
term it. Compare this modification of the examples on the plot.locfit  
help page:

x1 <- rnorm(1000) ; x2 <- rnorm(1000)
y <- dnorm(abs(x1-x2)) + rnorm(1000) / 5
plot(locfit(y~x1+x2), band="global")  # regression
plot(locfit(~x1+x2), band="global") # joint density

I do not that the code for plot.locfit appears to be using base  
graphics, although the help page suggests that trellis graphics will  
be used. I was not able to get an xlab or ylab to appear.