How to extrapolate beyond x points passed to `ksmooth`?

I have a kernel function like this:

x <- 1:100 y <- rnorm(100, mean=(x/2000)^2) plot(x,y) kernel <- ksmooth(x,y, kernel="normal", bandwidth=10) print(kernel$y) 

If I try to predict at a point outside the range of x values, she will give me NaN , because she is trying to extrapolate data beyond:

 x <- 1:100 y <- rnorm(100, mean=(x/2000)^2) plot(x,y) kernel <- ksmooth(x,y, kernel="normal", bandwidth=10, x.points=c(130)) print(kernel$y) > print(kernel$y) [1] NA 

Even when I change range.x , it does not budge:

 x <- 1:100 y <- rnorm(100, mean=(x/2000)^2) plot(x,y) kernel <- ksmooth(x,y, kernel="normal", bandwidth=10, range.x=c(1,200) , x.points=c(130)) print(kernel$y) > print(kernel$y) [1] NA 

How to get ksmooth extrapolation beyond data? I know that this is a bad idea in theory, but in practice this problem arises constantly.

+5
source share
1 answer

To answer your question by looking at the ksmooth code, range.x is only used when x.points not specified, which explains why you don't see it. Let's look at the code in ksmooth :

 function (x, y, kernel = c("box", "normal"), bandwidth = 0.5, range.x = range(x), n.points = max(100L, length(x)), x.points) { if (missing(y) || is.null(y)) stop("numeric y must be supplied.\nFor density estimation use density()") kernel <- match.arg(kernel) krn <- switch(kernel, box = 1L, normal = 2L) x.points <- if (missing(x.points)) seq.int(range.x[1L], range.x[2L], length.out = n.points) else { n.points <- length(x.points) sort(x.points) } ord <- order(x) .Call(C_ksmooth, x[ord], y[ord], x.points, krn, bandwidth) } 

From this we see that we do not need to provide x.points to make sure range.x used. If you run:

 x <- 1:100 y <- rnorm(100, mean=(x/2000)^2) plot(x,y) kernel <- ksmooth(x,y, kernel="normal", bandwidth=10, range.x=c(1,200)) plot(kernel$x, kernel$y) 

Now you will see that your core is rated over 100 (although not up to 200). Increasing the bandwidth setting allows you to get even more from 100.

+2
source

Source: https://habr.com/ru/post/1247846/


All Articles