Skip to content

Instantly share code, notes, and snippets.

@emhart
Created June 5, 2014 21:12
Show Gist options
  • Save emhart/1d5edf963a1c35e1e275 to your computer and use it in GitHub Desktop.
Save emhart/1d5edf963a1c35e1e275 to your computer and use it in GitHub Desktop.
A K-Nearest neighbor curve fitting function.
knnCont <- function(X, y, k = 4){
y <- y[order(X)]
X <- sort(X)
x.out <- vector()
y.out <- vector()
for(x in 1:(length(X)-(k-1))){
x.out <- c(x.out,mean(X[x:(x+(k-1))]))
y.out <- c(y.out,mean(y[x:(x+(k-1))]))
}
return(cbind(x.out,y.out))
}
X <- runif(1000,0,10)
y <- cbind(rep(1,length(X)),X)%*%c(1,2) + rnorm(1000,0,1)
y <- sin(X) + rnorm(1000,0,.1)
test <- knnCont(X,y,k=100)
plot(X,y)
lines(test,col=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment