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

使用R中nlme包lme()混合模型预测新值时遇错误的求助

问题描述

数据结构

原数据结构如下:

str(growth_data)
tibble [92 × 4] (S3: tbl_df/tbl/data.frame)
 $ person: num [1:92] 1 1 1 1 2 2 2 2 3 3 ...
 $ gender: chr [1:92] "F" "F" "F" "F" ...
 $ growth: num [1:92] 21 20 21.5 23 21 21.5 24 25.5 20.5 24 ...
 $ age   : Factor w/ 4 levels "8","10","12",..: 1 2 3 4 1 2 3 4 1 2 ...

拟合的混合模型

使用nlme包的lme()函数构建模型:

# 拟合含随机系数和非结构化协方差结构的混合模型
unstructured_rand <- nlme::lme(growth ~ gender*age, 
                     random = ~ age | person, 
                     data=growth_data, 
                     correlation = corSymm())

预测尝试与错误

尝试生成个体在新年龄的预测值,代码如下:

newGrowth <- expand.grid(
  person = unique(growth_data$person),
  gender = c("F","M"),
  age = c(13,15,17,20)
)

newGrowth$Predicted_Response <- predict(unstructured_rand, newdata = newGrowth)

运行后出现错误:

Error in `Names<-.pdMat`(`*tmp*`, value = value[[i]]) : 
  Length of names should be 4

问题原因与解决方案

核心原因

模型中的age是因子变量,原数据里age仅包含4个水平,而你在newGrowth中传入的13,15,17,20都是原因子水平之外的新值。由于模型的random = ~ age | person是基于原因子的4个水平构建的随机系数,corSymm()的非结构化协方差结构也对应每个个体的4个观测,新年龄水平不在预设结构内,导致模型无法匹配随机效应与协方差结构,触发错误。

解决方案

方案1:将age转换为连续变量重新建模(推荐)

若年龄适合作为连续变量分析,重新拟合模型:

# 将原因子型age转换为数值型
growth_data$age_num <- as.numeric(as.character(growth_data$age))

# 重新拟合混合模型
unstructured_rand_cont <- nlme::lme(growth ~ gender*age_num, 
                     random = ~ age_num | person, 
                     data=growth_data, 
                     correlation = corSymm())

# 构建包含新年龄的预测数据集
newGrowth_cont <- expand.grid(
  person = unique(growth_data$person),
  gender = c("F","M"),
  age_num = c(13,15,17,20)
)

# 生成预测结果
newGrowth_cont$Predicted_Response <- predict(unstructured_rand_cont, newdata = newGrowth_cont)

此方式下模型可对任意连续年龄值生成预测,随机效应与协方差结构均能适配连续变量的特性。

方案2:扩展原因子的水平(仅当年龄必须为因子时)

若必须保留age为因子类型,需先扩展原数据的因子水平再重新建模:

# 扩展原age变量的因子水平,加入目标新年龄
growth_data$age <- factor(growth_data$age, levels = c(levels(growth_data$age), "13","15","17","20"))

# 重新拟合模型
unstructured_rand_exp <- nlme::lme(growth ~ gender*age, 
                     random = ~ age | person, 
                     data=growth_data, 
                     correlation = corSymm())

# 构建预测数据集,确保age的格式与原数据一致
newGrowth_exp <- expand.grid(
  person = unique(growth_data$person),
  gender = c("F","M"),
  age = c("13","15","17","20"),
  stringsAsFactors = FALSE
)
# 同步因子水平
newGrowth_exp$age <- factor(newGrowth_exp$age, levels = levels(growth_data$age))

# 生成预测结果
newGrowth_exp$Predicted_Response <- predict(unstructured_rand_exp, newdata = newGrowth_exp)

注意:此方式下原数据无新年龄的观测,模型对新因子水平的估计依赖编码方式,随机效应部分会默认使用群体水平参数,预测可靠性弱于连续变量方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:19:58