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

R语言Swimmer Plot报错:data.frame行长度不一致问题求助

问题解决:Swimmer Plot报错“arguments imply differing number of rows: 1, 0”

报错原因分析

  • 错误的日期格式转换:初始创建study_7时已通过as.Date()将日期列转为Date类型,但后续用format = "%m/%d/%y"重新转换,该格式与原数据的YYYY-MM-DD格式不匹配,导致ther_start_date和ther_end_date被错误转为NA,进而使ther_start和ther_end计算出异常值。
  • 零长度治疗区间:部分治疗的ther_end_date与下一个治疗的ther_start_date完全相同(如study_id=8的多组治疗),计算后ther_end等于ther_start,形成长度为0的区间,触发swimplot内部的数据框行数不匹配错误。

修正后的代码

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()

# 计算以年为单位的时间差,同时处理零长度区间(给end加1天避免长度为0)
study_7 <- study_7 %>%
  mutate(
    # 给ther_end_date加1天,确保所有区间都有有效长度
    ther_end_date_adjusted = ther_end_date + 1,
    ther_start = as.numeric(difftime(ther_start_date, date_start_ther, units = "days")) / 365.25,
    ther_end = as.numeric(difftime(ther_end_date_adjusted, date_start_ther, units = "days")) / 365.25
  )

# 绘制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)

关键修改点

  1. 删除错误的as.Date(..., format = "%m/%d/%y")转换步骤,保留原始正确的Date类型列。
  2. 新增ther_end_date_adjusted列,给每个治疗的结束日期加1天,确保所有治疗区间都有有效长度,避免零长度区间触发的内部错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:58:15