我正在尝试使用JMbayes软件包拟合纵向和事件发生时间数据的联合模型,以预测随着时间的推移越来越多的症状数据可导致心脏骤停的风险。首先,我要拟合一个单变量模型,但是我的目标是在运行代码后合并许多纵向结果,这就是为什么我使用mvJointModelBayes()函数的原因。
但是,当我运行时,我尝试运行该函数时遇到以下错误。
{中的错误: 任务1失败-“加法:矩阵尺寸不兼容:500x1和3000x1”
我使用了与mvJMBayes小插图中提供的相同的代码,并使用了pbc2数据,该代码适用于我的数据集,但仍然遇到错误。我找不到任何明显的方式来导致我的数据框与pbc2数据集不同而导致错误。
library(tidyverse)
library(JMbayes)
library(lattice)
library(MASS)
# SIMULATE DATA AND SHAPE FOR MODELLING -------------------
id <- 1:500
gender <- sample(c('Male','Female'), 500, replace = TRUE, prob = c(0.51, 0.49))
status <- sample(c(0,1), 500, replace = TRUE, prob = c(0.9, 0.1))
survival_days <- rnorm(500)
angina1 <- sample(c(0,1), 500, replace = TRUE, prob = c(0.9, 0.1))
angina2 <- sample(c(0,1), 500, replace = TRUE, prob = c(0.8, 0.2))
angina3 <- sample(c(0,1), 500, replace = TRUE, prob = c(0.7, 0.3))
# Wide format for survival modelling. Single row per patient.
data_wide <- as.data.frame(
cbind(id, gender, status, survival_days, angina1, angina2, angina3))
# Recode factor levels
data_wide$survival_days<- as.numeric(data_wide$survival_days)
data_wide$status <- as.numeric(data_wide$status)
# Long format for longitudinal modelling.
data_long <- data_wide %>% gather(angina1:angina3, key = "timepoint", value = "angina")
data_long$timepoint <- str_replace(data_long$timepoint,"angina","")
data_long <- data_long %>% mutate(angina = as.factor(angina), timepoint = as.numeric(timepoint))
# MODELLING ---------------------------------------------------
set.seed(123)
mixed_model_fit <- mvglmer(list(angina ~ timepoint + (timepoint | id)), data = data_long, families = list(binomial))
cox_fit <- coxph(Surv(survival_days, status) ~ gender, data = data_wide, model = TRUE)
JMFit <- mvJointModelBayes(mixed_model_fit, cox_fit, timeVar = "timepoint")
上面代码的最后一部分返回:
{中的错误: 任务1失败-“加法:矩阵尺寸不兼容:500x1和3000x1”
有人能阐明如何解决此错误吗?
答案 0 :(得分:0)
我发现,如果id
是一个数字变量而不是一个因子,并且id
在两个数据集中以相同的顺序出现,它将起作用。在模型拟合之前运行以下代码即可解决问题:
data_long <- data_long %>%
mutate(id = as.numeric(id)) %>%
arrange(id)
data_wide <- data_wide %>%
mutate(id = as.numeric(id)) %>%
arrange(id)