n <- 100
x <- sort(runif(n))
y <- sin(pi*x) + rnorm(n)/10
str(ve <- varNPreg(x,y))
plot(x, y)
## "fitted" = y - residuals:
lines(x, y - ve$res, col=adjustcolor(2, 1/2), lwd=3)
segments(x,y,x,y-ve$res, col=3:4, lty=2:3, lwd=1:2)
## sigma2 := 1/n sum_i res_i^2 :
with(ve, c(sigma2, sum(res^2)/n))
stopifnot(with(ve, all.equal(sigma2, sum(res^2)/n)))
## show how 'snr' is computed, given 'sigma2' { in ../src/auxkerns.f }
dx2 <- diff(x, 2) # (x[i+1] - x[i-1]) i= 2..{n-1}
dx.n <- c(x[2]-x[1], dx2, x[n]-x[n-1])
SY <- sum(dx.n * y)
SY2 <- sum(dx.n * y^2)
rx <- 2*(x[n]-x[1]) # 'dn'
(sigm2.0 <- SY2/rx - (SY/rx)^2)
(R2 <- 1 - ve$sigma2 / sigm2.0)
stopifnot(all.equal(ve$snr, R2))
Run the code above in your browser using DataLab