R - 从lmer模型中提取ns样条对象并预测新数据

时间:2016-12-07 15:45:11

标签: r regression spline predict lme4

我希望从lmer模型预测'术语',特别是ns样条。我已经用mtcars数据集复制了这个问题(技术上很差的例子,但是可以解决这个问题)。

以下是我尝试使用线性模型的内容:

[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: RepositoryAttribute("Your.Namespace.Here")]

完美。但是,没有相应的条款' lmer的选项预测(unresolved issue here)。

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

鉴于没有等效的'预测,术语'功能,我将提取上面的固定和随机系数并将系数应用于mtcars数据,但不知道如何从模型中提取ns样条对象和&#39;预测&#39;一些新的数据。对于“聚合物”来说也是如此。转换变量,例如。 poly(drat,2) - 如果你能得到它,还有额外的荣誉。

1 个答案:

答案 0 :(得分:1)

自己动手并不困难。

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"

如果我们想要预测ns字词,请执行

## 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")

enter image description here