[R] difference between ns and bs in predict.glm

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Sep 2 00:32:06 CEST 2006


Your example is not actually a regression, and not reproducible.  Here is 
one that is both:

> fm1 <- lm(weight ~ ns(height, df = 5), data = women)
> predict(fm1, newdata=women[1,], se=TRUE)
Error: variable 'ns(height, df = 5)' was fitted with class "nmatrix.5" but 
class "nmatrix.1" was supplied
In addition: Warning message:
'newdata' had 1 rows but variable(s) found have 5 rows

It is only a problem if you try to predict from a single case.
Now take a look at

> attr(terms(fm1), "predvars")[[3]]
ns(height, knots = c(60.8, 63.6, 66.4, 69.2), Boundary.knots = c(58, 72), 
   intercept = FALSE)

If you apply that, you will get strange results: it is a bug in ns()  when 
applied to a length-one variable: a drop=TRUE is missing in

    basis <- as.matrix((t(qr.qty(qr.const, t(basis))))[,  - (1:2)])

On Fri, 1 Sep 2006, Spencer Jones wrote:

> I am fittling a spline to a variable in a regression model, I am then using
> the predict.glm funtion to make some predictions. When I use bs to fit the
> spline I don't have any problems using the predict.glm function however when
> I use ns I get the following error:
> 
> 
> Error in model.frame(formula, rownames, variables, varnames, extras,
> extranames,  :
>         variable lengths differ (found for 'ns(DY, df = 6)')
> In addition: Warning message:
> 'newdata' had 1 rows but variable(s) found have 6 rows
> 
> so for whatever reason this code works
> 
> 
> model. <- glm.nb(CNT ~ WKDY + bs(DY,df=6) + H_FLAG + NH_FLAG + Trend)
> predict(model,newdata=data[i,1:10],type="response",se=TRUE)
> 
> but this code does not work
> 
> model. <- glm.nb(CNT ~ WKDY + ns(DY,df=6) + H_FLAG + NH_FLAG + Trend)
> predict(model,newdata=data[i,1:10],type="response",se=TRUE)
> 
> the two are identical aside from bs vs ns. I looked at the R help and from
> what I could tell, both functions are based on splines.des and they output a
> matrix of the same dimension.
> Any feedback would be appreciated.
> 
> thanks,
> 
> Spencer
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list