R - Extract ns spline object from lmer model and predict on new data

纵然是瞬间 提交于 2021-02-07 10:31:19

问题


I'm looking to predict 'terms', especially ns splines, from an lmer model. I've replicated the problem with the mtcars dataset (technically poor example, but works to get the point across).

Here is what I'm trying to do with a linear model:

data(mtcars)
mtcarsmodel <- lm(wt ~ ns(drat,2) + hp + as.factor(gear), data= mtcars)
summary(mtcarsmodel)
coef(mtcarsmodel)
test <- predict(mtcarsmodel, type = "terms")

Perfect. However, there is no equivalent 'terms' option for lmer predict (unresolved issue here).

mtcarsmodellmer <- lmer(wt ~ ns(drat,2) + (hp|as.factor(gear)), data= mtcars)
summary(mtcarsmodellmer)
coef(mtcarsmodellmer)
ranef(mtcarsmodellmer) 

Given there is no equivalent ‘predict, terms’ function, I was going to extract the fixed and random coefficients above and apply the coefficients to the mtcars data, but have no idea on how to extract an ns spline object from a model and 'predict' it to some new data. The same goes for a 'poly' transformed variable eg. poly(drat, 2) - extra kudos if you can get this as well.


回答1:


It is not difficult to do it yourself.

library(lme4)
library(splines)
X <- with(mtcars, ns(drat, 2))  ## design matrix for splines (without intercept)
## head(X)
#             1          2
#[1,] 0.5778474 -0.1560021
#[2,] 0.5778474 -0.1560021
#[3,] 0.5738625 -0.1792162
#[4,] 0.2334329 -0.1440232
#[5,] 0.2808520 -0.1704002
#[6,] 0.0000000  0.0000000

## str(X)
# ns [1:32, 1:2] 0.578 0.578 0.574 0.233 0.281 ...
# - attr(*, "dimnames")=List of 2
#  ..$ : NULL
#  ..$ : chr [1:2] "1" "2"
# - attr(*, "degree")= int 3
# - attr(*, "knots")= Named num 3.7
#  ..- attr(*, "names")= chr "50%"
# - attr(*, "Boundary.knots")= num [1:2] 2.76 4.93
# - attr(*, "intercept")= logi FALSE
# - attr(*, "class")= chr [1:3] "ns" "basis" "matrix"

fit <- lmer(wt ~ X + (hp|gear), data= mtcars)

beta <- coef(fit)
#$gear
#           hp (Intercept)        X1         X2
#3 0.010614406    2.455403 -2.167337 -0.9246454
#4 0.014601363    2.455403 -2.167337 -0.9246454
#5 0.006342761    2.455403 -2.167337 -0.9246454
#
#attr(,"class")
#[1] "coef.mer"

If we want to predict the ns term, just do

## use `predict.ns`; read `?predict.ns`
x0 <- seq(1, 5, by = 0.2)  ## example `newx`
Xp <- predict(X, newx = x0)  ## prediction matrix
b <- with(beta$gear, c(X1[1], X2[1]))  ## coefficients for spline
y <- Xp %*% b  ## predicted mean

plot(x0, y, type = "l")



来源:https://stackoverflow.com/questions/41021658/r-extract-ns-spline-object-from-lmer-model-and-predict-on-new-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!