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

R语言基于前序行差值新增行:调整rvest提取的医疗表格结构

实现代码(基于dplyr)

library(tidyverse)

result <- data %>%
  group_by(date) %>%
  # 提取每日ICU通气患者总数
  mutate(vent_count = sum(patient_count[ward == "of which ventilated"], na.rm = TRUE)) %>%
  ungroup() %>%
  # 拆分普通行和通气标识行分别处理
  group_split(ward == "of which ventilated") %>%
  list_modify(
    # 处理非通气行:ICU总人数减去通气数得到非通气ICU人数,标记ventilated为FALSE
    `1` = .[[1]] %>%
      mutate(
        patient_count = ifelse(ward == "ICU", patient_count - vent_count, patient_count),
        ventilated = FALSE
      ) %>%
      select(-vent_count),
    # 处理通气标识行:归属到ICU病区,标记ventilated为TRUE
    `2` = .[[2]] %>%
      mutate(
        ward = "ICU",
        ventilated = TRUE
      ) %>%
      select(-vent_count)
  ) %>%
  bind_rows() %>%
  # 按日期排序匹配你需要的输出格式
  arrange(date, desc(ventilated), ward)

逻辑说明

  • 先按日期分组统计每日ICU通气患者总数,用于计算非通气ICU的实际人数
  • 拆分原数据中of which ventilated行和其他行分别处理:
    • 原ICU行的计数是ICU总人数,减去同日期通气人数就是非通气ICU人数,other病区人数无需调整
    • 通气标识行本质属于ICU病区,直接修改ward字段为ICU,保留原有计数作为通气ICU人数
  • 合并两类行后排序即可完全匹配你期望的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:54:02