0

I got a problem while trying to approximate the functional form of a density in R with approxfun(). The minimal example is as follows.

Example = seq(0.5, 1.5, 0.005)
dens = density(Example)
estim = approxfun(dens) 
plot(estim)
plot(dens) 

The problem is that plot(estim)gives the following plot enter image description here

but plot(dens)gives the full plot,

enter image description here

with the x-axis covering all values and not stopping at 1 as with the approxfun plot. Hence, approxfun() does not appropriately capture the density.

What am I doing wrong here? I did try several configurations of approxfun in order to somehow include the whole x-axis but without success.

Taufi
  • 1,557
  • 8
  • 14

1 Answers1

1

Your estim variable is just a function at that point. It doesn't remember the range of data that was used to create it. When plotting a function, you will need to tell R where to start and stop (By default R will plot a function from x=0 to x=1). For example

plot(estim, xlim=range(Example))

enter image description here

Note that range(Example) only covers the observed range. If you want to use the same range as the density plot, use

plot(estim, xlim=range(dens$x))

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks! I wasn't aware of the `range()` command in the plot function. I always changed it in the `approxfun()` command. – Taufi May 24 '18 at 20:53