linterp <- function (x1, y1, x2, y2) {
m <- (y2-y1)/(x2-x1)
b <- y2 - m*x2
## Convert into a form suitable for horner
return (c(b, m)) }
pwiselinterp <- function (x, y) {
n <- length(x) - 1
y <- y[order(x)]
x <- x[order(x)]
mvec <- bvec <- c()
for(i in 1:n) {
p <- linterp(x[i], y[i], x[i + 1], y[i + 1])
mvec <- c(mvec,p[2])
bvec <- c(bvec,p[1]) }
return(list(m = mvec , b = bvec )) }
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
pwiselinterp(x, y)
$m
[1] -1 1 3
$b
[1] -3 -1 -1
DataPlotLinear <- function(x,y) {
n = length(x)
xplotmin <- x[1]-1
xplotmax <- x[n]+1
yplotmin <- min(c(min(y),0))-1
yplotmax <- max(y)+1
plot(x,y,
main = "Data Plot",
xlab="x",ylab="y",type="p",lwd=3,col="blue",
xlim = c(xplotmin,xplotmax),
ylim = c(yplotmin,yplotmax) )
lines(x,y,type = "l",col="red",lwd=2)}
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
pwiselinterp(x, y)
$m
[1] -1 1 3
$b
[1] -3 -1 -1
DataPlotLinear(x,y)
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
f <- approxfun(x, y)
f(0.8)
[1] 1.4
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
f <- approxfun(x, y)
f(0.8)
[1] 1.4
DataPlotLinear(x,y)
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
spline.ex <- splinefun(x, y, method = "natural")
spline.ex(x)
[1] -1 -2 -1 2
spline.ex(0.8)
[1] 1.3232
library(pracma)
CubicSplinePlot <- function(x,y) {
n = length(x); N <- 100
t <- linspace(x[1], x[n], N)
p <- cubicspline(x, y, t)
bottom = min(0,min(p)); top = max(0,max(p))
plot(t,p,
main = "Cubic Spline",
xlab="x",ylab="y",type="l",lwd=2,col="red",
xlim = c(x[1],x[n]), ylim = c(bottom, top) )
points(x,y,type = "p",col="blue",lwd=3)
legend("topleft",
legend = c("Data", "Cubic Spline"),
col=c("blue","red"),
lty=c(1,1) )}
x <- c(-2, -1, 0, 1)
y <- c(-1, -2, -1, 2)
spline.ex(0.8)
[1] 1.3232
CubicSplinePlot(x,y)
#loading the Splines Packages
require(splines)
#ISLR contains the Dataset
require(ISLR)
attach(Wage) #attaching Wage dataset
#?Wage #for more details on the dataset
agelims<-range(age)
#Generating Test Data
age.grid<-seq(from=agelims[1], to = agelims[2])
#3 cutpoints at ages 25 ,50 ,60
fit<-lm(wage ~ bs(age,knots = c(25,40,60)),data = Wage )
#summary(fit)
#Plotting the Regression Line to the scatterplot
plot(age,wage,col="grey",xlab="Age",ylab="Wages")
points(age.grid,predict(fit,newdata = list(age=age.grid)),col="darkgreen",lwd=2,type="l")
#adding cutpoints
abline(v=c(25,40,60),lty=2,col="darkgreen")