如何使用R的cuminc函数指定累积发病率曲线的特定时间点?
解决
cuminc()指定时间点及绘图刻度问题 核心解决方案
要实现指定时间点输出累积发病率并在图中显示对应刻度,分两步操作:正确使用cuminc()的timepoint参数,以及自定义绘图的x轴刻度。
完整修正代码
首先确保加载cmprsk包(cuminc()函数属于该包):
library(cmprsk)
1. 模拟数据集(修正拼写错误)
# Set the sample size n <- 8076 # Create a variable for follow-up time time <- c(rep(180,6533),sample(1:179,n-6533,replace = TRUE)) # Create a variable for status status <- ifelse(time==180,0,1) # 0= alive/censored, 1 = death # Create age age <- sample(18:90,n,replace = TRUE) # Create gender sex <- sample(c("male","female"),n,replace = TRUE) # Combine df <- data.frame(time,status,age,sex)
2. 指定时间点计算累积发病率
直接将目标时间点向量传入cuminc()的timepoint参数:
# Cumulative incidence function with specified time points fit <- cuminc(time = df$time, status = df$status, group = df$sex, timepoint = c(0, 30, 90, 180)) print(fit)
运行print(fit)后,输出结果会仅展示0、30、90、180这几个时间点的累积发病率数值。
3. 绘图并设置自定义x轴刻度
xlim仅用于设置x轴范围(需传入最小值和最大值),要显示指定刻度需用axis()函数手动添加:
# Plot the cumulative incidence curves with custom x-axis ticks plot(fit, xlab = "Days", ylab = "Cumulative incidence", ylim = c(0, 0.4), xlim = c(0, 180)) # 限定x轴范围覆盖目标时间点 axis(1, at = c(0, 30, 90, 180)) # 替换默认刻度为指定时间点
常见错误说明
- 用
xlim=c(0,30,90,180)报错:xlim参数仅接受两个数值(x轴的最小、最大值),不能传入多个刻度点; - 直接写
timepoint(c(0,30,90,180)):这是语法错误,需将时间点向量作为cuminc()的timepoint参数传入函数内部。
内容的提问来源于stack exchange,提问作者user21637271
相关产品推荐
相关产品推荐

