R语言Swimmer Plot报错:参数暗示行数不一致问题求助
问题排查与修复方案
报错根源分析
报错Error in data.frame(id_fix, start_blank, end_blank): arguments imply differing number of rows: 1, 0的核心原因有两个:
- 日期格式转换错误:原始数据中
ther_start_date和ther_end_date已经是Date类型,但后续代码错误地用%m/%d/%y格式重新转换,导致日期变为NA,进而使ther_start和ther_end计算结果异常。 - 部分治疗区间长度为0:部分记录的
ther_start_date与ther_end_date完全相同(如study_id=7的最后一条A治疗、study_id=8的第一条A治疗),计算后ther_start等于ther_end,函数处理空白间隔时出现行不匹配。
修复后的完整代码
library(swimplot) library(ggplot2) library(dplyr) # 示例数据 study_7 <- data.frame( study_id = c(7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8), ther_type = c("S", "S", "S", "S", "E", "E", "E", "A", "A", "A", "A", "A"), ther_start_date = as.Date(c("2016-02-01", "2016-02-18", "2016-02-20", "2016-02-26", "2021-03-26", "2021-10-15", "2021-11-04", "2023-08-08", "2023-09-28", "2023-10-01", "2023-12-21", "2024-03-28")), ther_end_date = as.Date(c("2016-02-18", "2016-02-20", "2016-02-22", "2016-03-17", "2021-09-01", "2021-11-04", "2022-07-01", "2023-09-28", "2023-10-01", "2023-12-21", "2024-03-28", "2024-09-01")) ) # 为每个study_id计算最早治疗起始日期 study_7 <- study_7 %>% group_by(study_id) %>% mutate(date_start_ther = min(ther_start_date, na.rm=TRUE)) %>% ungroup() # 计算相对起始日期的年数差异(移除错误的日期格式转换步骤) study_7 <- study_7 %>% mutate( ther_start = as.numeric(difftime(ther_start_date, date_start_ther, units = "days")) / 365.25, ther_end = as.numeric(difftime(ther_end_date, date_start_ther, units = "days")) / 365.25 ) %>% # 过滤掉长度为0的无效治疗区间 filter(ther_end > ther_start) # 绘制Swimmer Plot study_plot <- swimmer_plot( df = study_7, id = 'study_id', start = "ther_start", end = "ther_end", name_fill = "ther_type", width = 0.85, color = NA, id_order = sort(unique(study_7$study_id), decreasing = TRUE) ) + theme_bw(base_size = 20) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(colour = "black")) + coord_flip(clip = 'off', expand = FALSE) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) # 查看绘图 print(study_plot)
关键修复点说明
- 删除错误的日期转换:原始数据创建时已经用
as.Date()生成了正确的日期格式,无需再次用错误的%m/%d/%y格式转换,避免生成NA值。 - 过滤无效区间:通过
filter(ther_end > ther_start)移除长度为0的治疗区间;如果需要保留这类记录,也可以用ther_end = ther_end + 0.001给区间加一个极小的长度,避免报错。 - 简化数据类型转换:无需将
study_7强制转为data.frame,dplyr处理后的tibble可直接被swimmer_plot识别。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

