code.R 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # install.packages("msm", repos = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/")
  2. library(msm)
  3. library(survival)
  4. # View(cav)
  5. data <- read.csv("paper_data.csv")
  6. # data$age_group <- cut(data$age,
  7. # breaks = c(45, 55, 65, Inf),
  8. # labels = c("45-54", "55-64",">=65"),
  9. # right = FALSE)
  10. data$gender_ <- factor(data$rgender, levels = c(1, 2), labels = c("男", "女"))
  11. summary(data$age_group)
  12. # View(data[, c("age", "age_group")])
  13. View(data$age_group)
  14. # 计算状态转移频数表
  15. freq_table <- statetable.msm(state, ID, data = data)
  16. print(freq_table)
  17. # 初始化转移速率矩阵
  18. qmatrix_init <- matrix(c(-0.5, 0.25, 0.15, 0.1,
  19. 0.1, -0.3, 0.1, 0.1,
  20. 0.3, 0.1, -0.5, 0.1,
  21. 0, 0, 0, 0),
  22. nrow = 4, byrow = TRUE)
  23. # 创建初始模型
  24. crude_init <- crudeinits.msm(state ~ wave, subject = ID, data = data, qmatrix = qmatrix_init)
  25. View(crude_init)
  26. # 进行多状态模型分析
  27. msm_model <- msm(state ~ wave, subject = ID, data = data,
  28. qmatrix = crude_init,
  29. covariates = ~ gender_,
  30. death = 4,
  31. method = "BFGS", control = list(fnscale = 4000, maxit = 10000)
  32. )
  33. # 计算状态转移概率矩阵
  34. prob_matrix <- pmatrix.msm(msm_model, t = 5) # t = 1 代表随访之间的间隔时间
  35. print(prob_matrix)
  36. # 输出拟合模型的速率矩阵
  37. q_matrix <- qmatrix.msm(msm_model)
  38. print(q_matrix)
  39. # 提取转移强度
  40. transition_intensity <- msm_model$qmatrix
  41. print(transition_intensity)
  42. # 计算在每个状态中的平均逗留时间
  43. so_journ <- sojourn.msm(msm_model)
  44. print(so_journ)
  45. # 计算均衡状态概率
  46. # 查看模型的详细结果
  47. summary(msm_model)
  48. rm(list = ls())