mcrGam: Monotone cr spline

View source: R/mcrGam.R

mcrGamR Documentation

Monotone cr spline

Description

Essentially group the line of codes in the example section of mgcv::pcls.

Usage

mcrGam(object, ...)

## S3 method for class 'gam'
mcrGam(object, increasing = TRUE, lower = NA, upper = NA, ...)

Arguments

object

[gam] output of the mgcv::gam function.

...

Not used. For compatibility with the generic function.

increasing

[logical] should the function should be constrained to be increasing. Otherwise it will be constrained to be decreasing.

lower

[numeric] This specifies the lower bound on the spline unless it is NA in which case no lower bound is imposed.

upper

[numeric] This specifies the upper bound on the spline unless it is NA in which case no upper bound is imposed.

Examples

if(require(mgcv)){

## Generate data from a monotonic truth.
set.seed(10)
x <- runif(100)*4-1;x <- sort(x);
f <- exp(4*x)/(1+exp(4*x)); y <- f+rnorm(100)*0.1; plot(x,y)
dat <- data.frame(x=x,y=y)

## Show regular spline fit (and save fitted object)

f.ug <- gam(y~s(x,k=10,bs="cr")); lines(x,fitted(f.ug))

## Create Design matrix, constraints etc. for monotonic spline....
sm <- smoothCon(s(x,k=10,bs="cr"),dat,knots=NULL)[[1]]
F <- mono.con(sm$xp);   # get constraints
G <- list(X=sm$X,C=matrix(0,0,0),sp=f.ug$sp,p=sm$xp,y=y,w=y*0+1)
G$Ain <- F$A;G$bin <- F$b;G$S <- sm$S;G$off <- 0
p <- pcls(G);  # fit spline (using s.p. from unconstrained fit)
fv<-Predict.matrix(sm,data.frame(x=x))%*%p
lines(x,fv,col=2)

## Proposed function
montone.f.ug <- mcrGam(f.ug)
monotone.pred <- predict(montone.f.ug)

if(require(testthat)){
expect_equal(montone.f.ug$mcr.p,p)
expect_equal(montone.f.ug$mcr.sm,sm)
expect_equal(monotone.pred,fv)
}

}

bozenne/butils documentation built on Oct. 14, 2023, 6:19 a.m.