You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含bs样条的glmerMod模型调用predict函数报错的原因与解决方法

问题:使用predict函数获取含splines::bs项的glmer模型拟合值时抛出错误

运行predict函数获取包含splines::bs项的glmer模型拟合值时,出现以下错误:

Error in `[.data.frame`(fr, vars) : undefined columns selected

可复现示例代码

# Reproducible example of glmer spline predict problem

library(tibble)
library(dplyr)
library(splines)
library(lme4)

## Simulate data
set.seed(1234L)

n_groups <- 100L

num_per_group <- rpois(n_groups, 50L) + 1L

group_mean <- rnorm(n_groups, sd = 0.2)

x_vals <- c(-20:19)

simulated_data <- tibble(x = sample(x_vals,
                                    sum(num_per_group),
                                    replace = TRUE),
                         group_no = rep(c(1:n_groups),
                                        num_per_group),
                         group_mean = rep(group_mean,
                                          num_per_group)) %>%
  arrange(x, group_no) %>%
  mutate(lin_pred = 3 - 0.05*abs(x) + group_mean,
         y = exp(lin_pred + rnorm(sum(num_per_group),
                                  mean = 0, sd = 0.1)),
         y = round(y))

# Fit model

glmer_spline <- glmer(y ~ bs(x,
                             knots = c(0),
                             degree = 1L) +
                        (1 | group_no),
                      data = simulated_data,
                      family = poisson(link = "log"),
                      control = glmerControl(optimizer="bobyqa")
)

summary(glmer_spline)

# This throws an error:
# Error in `[.data.frame`(fr, vars) : undefined columns selected

prediction_output_splines <- predict(glmer_spline,
                                     newdata = simulated_data,
                                     type = "response",
                                     allow.new.levels = TRUE,
                                     re.form=~0)

运行环境

  • R版本:4.2.3(2023-03-15)
  • 包版本:tibble 3.2.1、dplyr 1.1.2、lme4 1.1-34
  • 运行平台:RStudio "Mountain Hydrangea"(547dcf86, 2023-07-06)、macOS Ventura 13.4.1

需要确认的问题

  • 代码是否存在错误
  • 是否需要换用其他函数获取预测值
  • 需求是否存在不合理之处
  • 是否是相关R包的bug

内容的提问来源于stack exchange,提问作者HorridTom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:22:01