1. 核估计的话:
x<-c(1,2,4,7,11)
y<-c(9,0,3,2,7)h <- 0.055fx.hat <- function(z, h) { dnorm((z - x)/h)/h}NWSMOOTH <- function(h, y, x) { n <- length(y) s.hat <- rep(0, n) for (i in 1:n) { a <- fx.hat(x, h) s.hat <- sum(y * a/sum(a)) } return(s.hat)}
2. 局部多项式:
x<-c(1,2,4,7,11)
y<-c(9,0,3,2,7)h <-0.055
LPRSMOOTH <- function(y, x, h) { n <- length(y) s.hat <- rep(0, n) for (i in 1:n) { weight <- dnorm((x - x)/h) mod <- lm(y ~ x, weights = weight) s.hat <- as.numeric(predict(mod, data.frame(x = x))) } return(s.hat)}
3. 也可以用现成的函数loess()来做loess回归
loess(y~x,data,span)