# NOT RUN {
require(stats); require(graphics); require(splines)
nsx(women$height, df = 5)
summary(fm1 <- lm(weight ~ ns(height, df = 5), data = women))
## example of safe prediction
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, length.out = 200)
lines(ht, predict(fm1, data.frame(height=ht)))
# }
# NOT RUN {
<!-- % plotNsx <- function(obj,x,coef=c(-3,-4,2)) { -->
# }
# NOT RUN {
<!-- % ## numerical derivatives returning a function -->
# }
# NOT RUN {
<!-- % diff <- function(f,delta=1e-4,...) function(x) (f(x+delta,...)-f(x-delta,...))/(2*delta) -->
# }
# NOT RUN {
<!-- % par(mfrow=c(2,2)) -->
# }
# NOT RUN {
<!-- % plot(x,predict(obj,x)%*%coef,type="l",ylab="y",main="Natural spline") -->
# }
# NOT RUN {
<!-- % ## first derivative -->
# }
# NOT RUN {
<!-- % plot(x,diff(function(x) predict(obj,x) %*% c(0.1,-1,1))(x),type="l", -->
# }
# NOT RUN {
<!-- % ylab="y", main="First derivative") -->
# }
# NOT RUN {
<!-- % ## second derivative -->
# }
# NOT RUN {
<!-- % plot(x,diff(diff(function(x) predict(obj,x) %*% c(0.1,-1,1)))(x),type="l", -->
# }
# NOT RUN {
<!-- % ylab="y", main="Second derivative") -->
# }
# NOT RUN {
<!-- % } -->
# }
# NOT RUN {
<!-- % x=seq(0,12,length=100) -->
# }
# NOT RUN {
<!-- % plotNsx(nsx(1:10,df=3,derivs=c(2,2)),x) -->
# }
# NOT RUN {
<!-- % plotNsx(nsx(1:10,df=3,derivs=c(2,1)),x) -->
# }
# NOT RUN {
<!-- % plotNsx(nsx(1:10,df=3,derivs=c(1,1)),x) -->
# }
# NOT RUN {
<!-- % plotNsx(nsx(1:10,df=3,derivs=c(1,0)),x) # NB: predict(obj,Boundary.knot[1])==0.0 if intercept==FALSE -->
# }
# NOT RUN {
<!-- % rm(plotNsx,x) -->
# }
Run the code above in your browser using DataLab