Antoine
Antoine

Reputation: 1719

NA returned by approxfun() function R

obs=log(rexp(500))
plot(density(obs))

enter image description here

I am using the approxfun() R function to create a function capturing this distribution and able to return a y value for any x value passed (by using interpolation).

fun=approxfun(density(obs)$y)
# create a sequence of x values
seq=round(seq(min(obs),max(obs),length.out=50),2)
# find out which y values assigned by fun are not equal to NA
seq[-which(is.na(fun(seq)))]

returns

1.11 1.27 1.43 1.60

Why are all x values below 1 (from -6.38 to 0.95 to be exact) passed to the function all assigned a NA y value? The function is defined for -6, -2 etc? I would have expected interpolated values around 0, 0.13, etc. Not NAs...

Upvotes: 0

Views: 1037

Answers (1)

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10223

It should be something like:

fun <- approxfun(density(obs))

You don't supply the x-values when you write fun=approxfun(density(obs)$y). So, you should just omit the $y.

Hence:

obs <- log(rexp(500))
fun <- approxfun(density(obs))
seq <- round(seq(min(obs), max(obs), length.out = 50), 2)
seq[-which(is.na(fun(seq)))]
# numeric(0)

yields no NAs.

Upvotes: 1

Related Questions