前回までの資料も一部記載していますが、コードは最低限にしています。
復習は第1回資料を参照してください。

package

pacman::p_load(
  tidyverse,
  lubridate,
  tableone,
  skimr,
  duckdb,
  DBI,
  dbplyr,
  RSQLite
)

データベース

Fドライブの Database フォルダ内にある mimic_iv.db にアクセスします。
各自の環境に合わせて、必要であれば以下のパスを修正してください。

db_path <- "F:/Database/mimic_iv.db"
con_mimic <- DBI::dbConnect(duckdb::duckdb(), dbdir = db_path)

DB内に入っているテーブル一覧を確認します。

DBI::dbListTables(con_mimic)
##  [1] "admissions"                     "antibiotic"                    
##  [3] "apsiii"                         "bja_step01_patients_2026"      
##  [5] "bja_step02_po_2026"             "bja_step03_analysis_base_2026" 
##  [7] "caregiver"                      "charlson"                      
##  [9] "chartevents"                    "crrt"                          
## [11] "d_hcpcs"                        "d_icd_diagnoses"               
## [13] "d_icd_procedures"               "d_items"                       
## [15] "d_labitems"                     "datetimeevents"                
## [17] "diagnoses_icd"                  "dobutamine"                    
## [19] "dopamine"                       "drgcodes"                      
## [21] "emar"                           "emar_detail"                   
## [23] "epinephrine"                    "first_day_gcs"                 
## [25] "first_day_height"               "first_day_lab"                 
## [27] "first_day_rrt"                  "first_day_sofa"                
## [29] "first_day_urine_output"         "first_day_vitalsign"           
## [31] "first_day_weight"               "hcpcsevents"                   
## [33] "height"                         "icustay_detail"                
## [35] "icustays"                       "ingredientevents"              
## [37] "inputevents"                    "kdigo_creatinine"              
## [39] "kdigo_stages"                   "kdigo_uo"                      
## [41] "labevents"                      "microbiologyevents"            
## [43] "norepinephrine"                 "norepinephrine_equivalent_dose"
## [45] "oasis"                          "omr"                           
## [47] "outputevents"                   "patients"                      
## [49] "pharmacy"                       "phenylephrine"                 
## [51] "poe"                            "poe_detail"                    
## [53] "prescriptions"                  "procedureevents"               
## [55] "procedures_icd"                 "provider"                      
## [57] "rrt"                            "sapsii"                        
## [59] "sepsis3"                        "services"                      
## [61] "sofa"                           "transfers"                     
## [63] "vasoactive_agent"               "vasopressin"                   
## [65] "ventilation"                    "weight_durations"

最後に接続解除する場合は、以下を使います。

# DBI::dbDisconnect(con_mimic, shutdown = TRUE)

使用データ

第1回で作成した bja_step01_patients_2026 を使います。
このテーブルは、成人・初回ICU stay・Sepsis-3患者まで絞ったデータです。

input_table <- "bja_step01_patients_2026"

if (!DBI::dbExistsTable(con_mimic, input_table)) {
  stop(paste0(
    input_table,
    " がDB内にありません。第1回資料の保存コードを実行してから進めてください。"
  ))
}

db_bja_step01 <- tbl(con_mimic, input_table)

db_bja_step01 |> colnames()
##  [1] "subject_id"               "hadm_id"                 
##  [3] "stay_id"                  "age"                     
##  [5] "gender"                   "race"                    
##  [7] "admission_type"           "admission_location"      
##  [9] "discharge_location"       "insurance"               
## [11] "language"                 "marital_status"          
## [13] "hospital_expire_flag"     "admittime"               
## [15] "dischtime"                "deathtime"               
## [17] "dod"                      "first_careunit"          
## [19] "last_careunit"            "icu_intime"              
## [21] "icu_outtime"              "icu_los"                 
## [23] "suspected_infection_time" "sofa_time"               
## [25] "sofa_score"               "respiration"             
## [27] "coagulation"              "liver"                   
## [29] "cardiovascular"           "cns"                     
## [31] "renal"
db_bja_step01 |> head(10)

第1回講義・課題:解答例

第2回では、BJA論文のPatientを完成させ、主要評価項目である28日全死亡を作成します。
まず第1回課題で整理した適格基準・除外基準を、順にデータへ反映します。

今回扱う追加条件は以下です。

  1. ICU滞在が24時間以下の患者を除外する
  2. Sepsis onset前のMg測定がない患者を除外し、高Mg血症がある患者を除外する
  3. ICU入室前に硫酸マグネシウムを投与された患者を除外する
  4. 主要評価項目である28日全死亡を作成する

1. ICU滞在時間:24時間以下を除外

icustays には los もありますが、除外基準を明確に再現するため、 ここでは icu_intime と icu_outtime からICU滞在時間を計算します。

db_bja_step02_icu_duration <- 
  db_bja_step01 |>
  mutate(
    icu_stay_hours = date_diff("second", icu_intime, icu_outtime) / 3600,
    exclude_icu_le_24h = icu_stay_hours <= 24
  )

db_bja_step02_icu_duration |>
  count(exclude_icu_le_24h)
db_bja_step02_after_icu_duration <- 
  db_bja_step02_icu_duration |>
  filter(exclude_icu_le_24h == FALSE)

db_bja_step02_after_icu_duration |>
  summarise(
    n_rows = n(),
    n_stays = n_distinct(stay_id),
    n_subjects = n_distinct(subject_id),
    icu_stay_hours_min = min(icu_stay_hours, na.rm = TRUE),
    icu_stay_hours_median = median(icu_stay_hours, na.rm = TRUE),
    icu_stay_hours_max = max(icu_stay_hours, na.rm = TRUE)
  )

2. Sepsis onset前の血清Mg値

BJA論文では、Sepsis onset前に高Mg血症がある患者を除外しています。
高Mg血症は serum magnesium > 1.07 mmol/L と定義されています。

MIMIC-IVの labevents では、Mg値の単位が mg/dL で格納されている可能性があります。
その場合、Mgの分子量を用いておおよそ以下のように換算します。

\[Mg (mmol/L) = Mg (mg/dL) / 2.43\]

したがって、論文のカットオフは以下に相当します。

  • 低Mg血症: < 0.66 mmol/L
  • 高Mg血症: > 1.07 mmol/L
  • mg/dL なら高Mg血症は約 > 2.60 mg/dL

今回は、Sepsis onset前にMg測定がない患者はMg分類ができないため除外します。
Mg測定がある患者のうち、1回でも高Mg血症があれば除外します。
低Mg血症は除外せず、サブグループとして扱います。

Mgのitemidを確認する

db_labitems <- tbl(con_mimic, "d_labitems")

df_mg_items <-
  db_labitems |>
  collect() |>
  filter(str_detect(str_to_lower(label), "magnesium"))

df_mg_items

血清Mgとして使うitemidを選びます。
尿中Mgなどが含まれている場合は除外します。 ここでは50960ですが、コードで呼び出した方が間違いが少ないです。

mg_itemids <-
  df_mg_items |>
  filter(str_to_lower(fluid) %in% c("blood", "serum", "plasma")) |>
  pull(itemid) |>
  unique()

mg_itemids
## [1] 50960

labeventsから、Sepsis onset前のMg値を抽出する

sepsis3 には、感染が疑われた時刻と、SOFAスコアがSepsis-3基準を満たした時刻が含まれています。

Sepsis-3は「感染疑い」と「臓器障害」の両方がそろって初めて成立するため、本演習では、2つの時刻のうち遅い方をSepsis onsetとして扱います。

このSepsis onsetを基準にして、Mg測定、高Mg血症の除外、Mg status、28日死亡を作成します。

Rコード上では、max(sofa_time, suspected_infection_time) に相当する処理を行います。

db_labevents <- tbl(con_mimic, "labevents")

db_bja_step02_base <-
  db_bja_step02_after_icu_duration |>
  mutate(
    sepsis_onset_time = case_when(
      is.na(sofa_time) ~ suspected_infection_time,
      is.na(suspected_infection_time) ~ sofa_time,
      sofa_time >= suspected_infection_time ~ sofa_time,
      TRUE ~ suspected_infection_time
    )
  )

BJA論文ではMg値を mmol/L で扱っているため、 MIMIC-IV上で mg/dL として格納されている場合は、 mg/dL / 2.43 により mmol/L に換算します。   (実際はほぼすべてmg/dLで格納されていました)

db_mg_labs <-
  db_labevents |>
  filter(
    itemid %in% mg_itemids,
    !is.na(valuenum)
  ) |>
  select(
    subject_id,
    hadm_id,
    itemid,
    charttime,
    valuenum,
    valueuom
  ) |>
  mutate(
    valueuom_lower = str_to_lower(valueuom),
    mg_mmol_l = case_when(
      valueuom_lower %in% c("mmol/l", "mmol/liter") ~ valuenum,
      valueuom_lower %in% c("mg/dl") ~ valuenum / 2.43,
      TRUE ~ valuenum
    )
  )

db_mg_labs |>
  count(valueuom)
db_mg_labs |> head(10)

MgSO4投与後のMg値を避けるための投与時刻を準備する

Mg statusは「Sepsis onset時点の状態」として扱います。
そのため、MgSO4投与後に測定されたMg値を使うと、曝露後の影響を受けた値で分類してしまう可能性があります。

このブロックでは、以下を行います。

  • MgSO4の初回投与時刻を作成する。
  • Mg値とMg statusの判定では、MgSO4投与時刻以降のMg値を使わない。
db_emar <- tbl(con_mimic, "emar")
db_inputevents <- tbl(con_mimic, "inputevents")
db_d_items <- tbl(con_mimic, "d_items")

eMARは、薬剤の投与記録を扱うテーブルです。
まず、medication からMgSO4らしい薬剤名を抽出します。

event_txt は、薬剤イベントの状態を表す列です。

# db_emar |> distinct(medication) |> collect() |> View()
db_emar |> head(10)

たとえば Administered、Started、Confirmed、Stopped、Not Given などが入ります。
ここでは「MgSO4投与後のMg値をMg status判定に使わない」ことが目的なので、 実投与または投与確認を示す可能性がある Administered / Started / Confirmed 系のイベントを候補にします。

df_emar_medication_for_mg_status <-
  db_emar |>
  distinct(medication) |>
  collect()

vec_mgso4_emar_for_mg_status <-
  df_emar_medication_for_mg_status |>
  filter(
    !is.na(medication),
    str_detect(str_to_lower(medication), "magnesium"),
    str_detect(str_to_lower(medication), "sulf|sulph"),
    !str_detect(
      str_to_lower(medication),
      "citrate|gluconate|oxide|hydroxide|chloride|lactate|calcium"
    )
  ) |>
  pull(medication) |>
  unique()

vec_mgso4_admin_event <- c(
  "Administered",
  "Administered in Other Location",
  "Delayed Administered",
  "Partial Administered",
  "Started",
  "Started in Other Location",
  "Delayed Started",
  "Restarted",
  "Confirmed",
  "Confirmed in Other Location",
  "Delayed Confirmed",
  "Documented in O.R. Holding"
)


db_mgso4_emar_time_for_mg_status <-
  db_bja_step02_base |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    icu_intime,
    icu_outtime
  ) |>
  inner_join(
    db_emar |>
      filter(
        medication %in% vec_mgso4_emar_for_mg_status,
        event_txt %in% vec_mgso4_admin_event
      ) |>
      select(subject_id, hadm_id, charttime),
    by = c("subject_id", "hadm_id")
  ) |>
  filter(
    charttime >= icu_intime,
    charttime <= icu_outtime
  ) |>
  transmute(
    subject_id,
    hadm_id,
    stay_id,
    first_mgso4_candidate_time = charttime,
    mgso4_source_for_mg_status = "emar"
  )
db_mgso4_emar_time_for_mg_status |> head(10)

次に、ICU内の投与・輸液記録である inputevents からMgSO4を探します。
inputevents では薬剤名そのものではなく itemid で記録されるため、 先に d_items から Magnesium Sulfate に該当する itemid を確認します。

db_inputevents |> head(10)
db_d_items |> filter(linksto == "inputevents") |> head(10)
df_mg_input_items_for_mg_status <-
  db_d_items |>
  filter(
    str_detect(str_to_lower(label), "magnesium") |
      str_detect(str_to_lower(abbreviation), "magnesium")
  ) |>
  select(itemid, label, abbreviation, category) |>
  collect()

df_mg_input_items_for_mg_status
mg_input_itemids_for_mg_status <-
  df_mg_input_items_for_mg_status |>
  filter(
    str_detect(str_to_lower(coalesce(label, "")), "magnesium sulfate"),
    category == "Medications"
  ) |>
  pull(itemid) |>
  unique()


db_mgso4_input_time_for_mg_status <-
  db_bja_step02_base |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    icu_intime,
    icu_outtime
  ) |>
  inner_join(
    db_inputevents |>
      filter(itemid %in% mg_input_itemids_for_mg_status) |>
      select(subject_id, hadm_id, stay_id, starttime, endtime, statusdescription),
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  filter(
    starttime < icu_outtime,
    is.na(endtime) | endtime > icu_intime,
    is.na(statusdescription) |
      !str_detect(str_to_lower(statusdescription), "rewritten|canceled|cancelled")
  ) |>
  transmute(
    subject_id,
    hadm_id,
    stay_id,
    first_mgso4_candidate_time = starttime,
    mgso4_source_for_mg_status = "inputevents"
  )
db_mgso4_input_time_for_mg_status |> head(10)

eMARとinputeventsの候補時刻を縦に結合し、ICU stayごとに最も早いMgSO4候補時刻を作ります。
この時刻は、MgSO4投与後のMg値をMg status判定から外すための補助情報です。
最終的なExposure定義そのものではありません。(第2回では、Sepsis onset前の投与も含めて、Mg status判定用の初回投与時刻を求めます。第3回では、Sepsis onset以後のMgSO4投与の有無でExposureを定義します。)

db_first_mgso4_for_mg_status <-
  db_mgso4_emar_time_for_mg_status |>
  union_all(db_mgso4_input_time_for_mg_status) |>
  group_by(subject_id, hadm_id, stay_id) |>
  summarise(
    first_mgso4_time_for_mg_status = min(first_mgso4_candidate_time, na.rm = TRUE),
    .groups = "drop"
  ) |>
  compute()


db_first_mgso4_for_mg_status |>
  summarise(
    n_stays_with_mgso4_time = n_distinct(stay_id)
  )

高Mg除外用のMg値と、onset時点のMg statusを作成する

ミニレクチャー:joinの使い分け

join は、複数のテーブルを結合するときに使います。
ただし、どの join を使うかによって、残る行と追加される列が変わります。

  • inner_join() は、両方のテーブルに共通して存在する行だけを残し、右側テーブルの列も追加します。
  • left_join() は、左側テーブルの行をすべて残し、右側テーブルの列を追加します。右側に対応する行がない場合、その列は NA になります。
  • semi_join() は、右側テーブルに対応する行がある左側の行だけを残します。ただし、右側テーブルの列は追加しません。(filtering joinと呼ばれる)

今回作りたいのは、「Sepsis onset前に測定されたMg値そのものを集めたデータ」です。
そのため、患者データにMg値や測定時刻を結合する必要があります。

ここでは inner_join() を使い、患者データとMg検査データを結合します。
この中間データには、Mg測定がある患者のMg測定行だけが含まれます。

Mg測定がない患者も、最終的には対象患者の流れの中で扱います。
そのため、後のステップでMg情報を患者データに戻すときには left_join() を使い、Mg測定がない患者は n_mg_before = 0 として明示します。

このブロックでは、Mg値を以下の目的で整理します。

  • 患者選択のために、Sepsis onset前のMg値を要約する。
  • Sepsis onset前に高Mg血症があれば、除外基準に該当すると判断する。
  • 層別解析やTable 1のために、Mg statusを低Mg血症または正常Mgに分類する。
  • Mg statusに使う値は、MgSO4投与前で、Sepsis onsetに最も近いMg値とする。
db_mg_before_sepsis <-
  db_bja_step02_base |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    icu_intime,
    sepsis_onset_time
  ) |>
  inner_join(
    db_mg_labs,
    by = c("subject_id", "hadm_id")
  ) |>
  filter(charttime < sepsis_onset_time) |> 
  compute()

db_mg_before_sepsis |>
  summarise(
    n_mg_rows = n(),
    n_stays_with_mg_before = n_distinct(stay_id)
  )
db_mg_before_sepsis |> head(10)

患者ごとに、Sepsis onset前のMg値をまとめます。

ここで作る変数の役割は以下です。

  • n_mg_before: Sepsis onset前にMg測定があるかを確認するために使う。
  • any_high_mg_before: Sepsis onset前に1回でも高Mg血症があれば1にする。これは除外基準に使う。
  • mg_status_at_onset: MgSO4投与前で、Sepsis onsetに最も近いMg値。これは低Mg血症/正常Mgの分類に使う。

患者選択は n_mg_before > 0 と any_high_mg_before == 0 で行います。
mg_status_at_onset はMg status分類のために使い、患者数を増減させる条件にはしません。

db_mg_before_summary_base <-
  db_mg_before_sepsis |>
  group_by(subject_id, hadm_id, stay_id) |>
  summarise(
    n_mg_before = n(),
    mg_before_min = min(mg_mmol_l, na.rm = TRUE),
    mg_before_max = max(mg_mmol_l, na.rm = TRUE),
    any_low_mg_before = max(if_else(mg_mmol_l < 0.66, 1L, 0L), na.rm = TRUE),
    any_high_mg_before = max(if_else(mg_mmol_l > 1.07, 1L, 0L), na.rm = TRUE),
    .groups = "drop"
  )


db_mg_before_summary_base |>
  count(any_low_mg_before, any_high_mg_before)

次に、Sepsis onset前の最新Mg値を取り出します。
これは、患者選択に使っている「Sepsis onset前Mg測定あり」の内容を確認するための補助情報として残します。 同じ時刻に複数のMg値がある場合は、その時刻の最大値を代表値として扱います。

db_mg_before_latest_time <-
  db_mg_before_sepsis |>
  group_by(subject_id, hadm_id, stay_id) |>
  summarise(
    mg_latest_before_time = max(charttime, na.rm = TRUE),
    .groups = "drop"
  )


db_mg_before_latest <-
  db_mg_before_sepsis |>
  inner_join(
    db_mg_before_latest_time,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  filter(charttime == mg_latest_before_time) |>
  group_by(subject_id, hadm_id, stay_id) |>
  summarise(
    mg_latest_before = max(mg_mmol_l, na.rm = TRUE),
    mg_latest_before_time = max(mg_latest_before_time, na.rm = TRUE),
    .groups = "drop"
  ) |> 
  compute()

db_mg_before_latest |> head(10)

charttimeはMg測定時刻。sepsis onsetより前、MgSO4投与よりも前の情報に限定する。

db_mg_status_candidate <-
  db_bja_step02_base |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    sepsis_onset_time
  ) |>
  left_join(
    db_first_mgso4_for_mg_status,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  inner_join(
    db_mg_labs,
    by = c("subject_id", "hadm_id")
  ) |>
  mutate(
    mg_seconds_from_onset = date_diff("second", sepsis_onset_time, charttime),
    mg_time_distance_seconds = abs(mg_seconds_from_onset)
  ) |>
  filter(
    charttime < sepsis_onset_time,
    is.na(first_mgso4_time_for_mg_status) |
      charttime < first_mgso4_time_for_mg_status
  ) |> 
  compute()

db_mg_status_candidate |> head(10)

複数のMg値がある場合、sepsis onsetに一番近いMg値に限定する

db_mg_status_at_onset <-
  db_mg_status_candidate |>
  group_by(subject_id, hadm_id, stay_id) |>
  window_order(mg_time_distance_seconds) |>
  mutate(mg_status_rank = row_number()) |>
  ungroup() |>
  filter(mg_status_rank == 1) |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    mg_status_at_onset = mg_mmol_l,
    mg_status_charttime = charttime,
    mg_seconds_from_onset,
    first_mgso4_time_for_mg_status
  )

db_mg_status_at_onset |> head(10)

ICU滞在ごとのMg集計に、Sepsis onset前の最新Mg値とMg statusの判定に使うMg値を結合し、それぞれの欠測数を確認します。

db_mg_before_summary <-
  db_mg_before_summary_base |>
  left_join(
    db_mg_before_latest,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  left_join(
    db_mg_status_at_onset,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |> 
  compute()

db_mg_before_summary |> head(10)
db_mg_before_summary |>
  summarise(
    n_rows = n(),
    n_missing_latest_mg =
      sum(if_else(is.na(mg_latest_before), 1L, 0L), na.rm = TRUE),
    n_missing_mg_status_at_onset =
      sum(if_else(is.na(mg_status_at_onset), 1L, 0L), na.rm = TRUE)
  )

Sepsis onset前にMg測定値がある13605件のICU滞在すべてで、発症前の最新Mg値が得られている。
108件は、onset前にMg測定はあったものの、記録上の初回MgSO4投与より前の測定値がなく、Mg statusを判定できない。(←ICU入室前にMgSO4投与されていた場合は除外されることになる)

第1回で作った患者データへMg情報を結合します。
db_mg_before_summary はMg測定がある患者だけを含むため、Mg測定がない患者ではMg関連列が NA になります。

coalesce(x, 0L) は、x が NA の場合に 0L に置き換える関数です。
ここでは、Mg測定がなかった患者を n_mg_before = 0 として明示し、その後で除外します。

db_bja_step02_mg <-
  db_bja_step02_base |>
  left_join(
    db_mg_before_summary,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  mutate(
    n_mg_before = coalesce(n_mg_before, 0L),
    any_low_mg_before = coalesce(any_low_mg_before, 0L),
    any_high_mg_before = coalesce(any_high_mg_before, 0L),
    mg_status_value = mg_status_at_onset
  ) |>
  mutate(
    has_mg_before = n_mg_before > 0L,
    magnesium_status_before = case_when(
      n_mg_before == 0L ~ "no_mg_before",
      any_high_mg_before == 1L ~ "hypermagnesemia",
      mg_status_value < 0.66 ~ "hypomagnesemia",
      mg_status_value <= 1.07 ~ "normomagnesemia",
      mg_status_value > 1.07 ~ "hypermagnesemia",
      TRUE ~ NA_character_
    )
  )


db_bja_step02_mg |>
  count(has_mg_before, magnesium_status_before)

any_low_mg_before は「Sepsis onset前に1回でも低Mgだったか」を示す確認用の変数として残しています。
一方、Table 1で使う magnesium_status_before は、Sepsis onset前のMg値だけを候補にし、時間制限を設けず、MgSO4投与前でonsetに最も近いMg値で分類します。

Mg測定がない患者を除外します。

db_bja_step02_mg_measured <-
  db_bja_step02_mg |>
  filter(has_mg_before == TRUE)

db_bja_step02_mg_measured |>
  summarise(
    n_rows = n(),
    n_stays = n_distinct(stay_id),
    n_subjects = n_distinct(subject_id)
  )

続いて、高Mg血症がある患者を除外します。

db_bja_step02_no_high_mg <-
  db_bja_step02_mg_measured |>
  filter(any_high_mg_before == 0L)

db_bja_step02_no_high_mg |>
  summarise(
    n_rows = n(),
    n_stays = n_distinct(stay_id),
    n_subjects = n_distinct(subject_id)
  )
db_bja_step02_no_high_mg |>
  count(magnesium_status_before)

3. ICU入室前の硫酸マグネシウム投与

BJA論文では、ICU入室前に硫酸マグネシウムを投与された患者を除外しています。
この演習では、主定義として emar と inputevents を使ってMgSO4投与を確認します。

emar は薬剤投与記録を確認するために使います。
一方、ICU内の輸液・持続投与は inputevents に記録されていることがあります。

薬剤名は表記ゆれがあるため、まず emar に含まれる薬剤名を確認します。

db_emar <- tbl(con_mimic, "emar")

db_emar |> colnames()
##  [1] "subject_id"        "hadm_id"           "emar_id"          
##  [4] "emar_seq"          "poe_id"            "pharmacy_id"      
##  [7] "enter_provider_id" "charttime"         "medication"       
## [10] "event_txt"         "scheduletime"      "storetime"
db_emar |> head(10)
# db_emar |> distinct(medication) |> collect() |> View()
df_emar_medication <-
  db_emar |>
  distinct(medication) |>
  collect()

vec_mgso4_emar <-
  df_emar_medication |>
  filter(
    !is.na(medication),
    str_detect(str_to_lower(medication), "magnesium"),
    str_detect(str_to_lower(medication), "sulf|sulph"),
    !str_detect(
      str_to_lower(medication),
      "citrate|gluconate|oxide|hydroxide|chloride|lactate|calcium"
    )
  ) |>
  pull(medication) |>
  unique()

vec_mgso4_emar
## [1] "Magnesium Sulfate (OB)"                                    
## [2] "Magnesium Sulfate Replacement (Critical Care and Oncology)"
## [3] "Magnesium Sulfate (L&D)"                                   
## [4] "Magnesium Sulfate 50 % Topical Soln"                       
## [5] "Magnesium Sulfate"

ICU入室前のMgSO4投与を抽出します。
event_txt は上で説明したように、投与・開始・確認・中止・未投与などの状態を表します。
ここでは、MgSO4候補にどのような event_txt が含まれるかをあらためて確認します。

db_mgso4_emar <-
  db_emar |>
  filter(medication %in% vec_mgso4_emar) |>
  select(
    subject_id,
    hadm_id,
    charttime,
    medication,
    event_txt
  )

db_mgso4_emar |> head(10)

次の集計で、MgSO4候補に含まれる event_txt の種類を確認します。

db_mgso4_emar |>
  count(event_txt, sort = TRUE) |>
  collect()

集計結果を見ると、MgSO4候補には Administered 系、Started 系、Confirmed 系、Stopped 系、Not Given 系などが含まれます。

ICU入室前MgSO4投与の除外では、投与開始・投与確認に加えて、 ICU入室前から投与が続いていた可能性を拾うため Stopped 系も広めに含めます。
一方、Not Given / Not Started などは、投与された根拠としては扱いません。

vec_mgso4_admin_event <- c(
  "Administered",
  "Administered in Other Location",
  "Delayed Administered",
  "Partial Administered",
  "Started",
  "Started in Other Location",
  "Delayed Started",
  "Restarted",
  "Confirmed",
  "Confirmed in Other Location",
  "Delayed Confirmed",
  "Documented in O.R. Holding"
)


vec_mgso4_stop_event <- c(
  "Stopped",
  "Stopped in Other Location",
  "Stopped - Unscheduled",
  "Stopped - Unscheduled in Other Location",
  "Not Stopped"
)

vec_mgso4_before_icu_exclusion_event <- c(
  vec_mgso4_admin_event,
  vec_mgso4_stop_event
)
db_mgso4_before_icu_emar_all_events <-
  db_bja_step02_no_high_mg |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    icu_intime
  ) |>
  inner_join(
    db_mgso4_emar,
    by = c("subject_id", "hadm_id")
  ) |>
  filter(charttime < icu_intime)

db_mgso4_before_icu_emar <-
  db_mgso4_before_icu_emar_all_events |>
  filter(event_txt %in% vec_mgso4_before_icu_exclusion_event)
db_mgso4_before_icu_emar |>
  summarise(
    n_rows = n(),
    n_stays_with_mgso4_before_icu_emar = n_distinct(stay_id)
  )

次に、inputevents からMgSO4投与を抽出します。
d_items で確認すると、Magnesium には検査値由来の項目も含まれます。
Exposureとして扱うのは投与薬剤なので、ここでは Magnesium Sulfate かつ Medications に該当するitemidだけを使用します。

db_inputevents <- tbl(con_mimic, "inputevents")
db_d_items <- tbl(con_mimic, "d_items")

df_mg_input_items <-
  db_d_items |>
  filter(
    str_detect(str_to_lower(label), "magnesium") |
      str_detect(str_to_lower(abbreviation), "magnesium")
  ) |>
  select(
    itemid,
    label,
    abbreviation,
    category,
    unitname,
    param_type,
    linksto
  ) |>
  collect()

df_mg_input_items
mg_input_itemids <-
  df_mg_input_items |>
  filter(
    str_detect(str_to_lower(coalesce(label, "")), "magnesium sulfate"),
    category == "Medications"
  ) |>
  pull(itemid) |>
  unique()

mg_input_itemids
## [1] 222011 227523 227524

inputevents の statusdescription も確認します。

db_mg_input_events <-
  db_inputevents |>
  filter(itemid %in% mg_input_itemids) |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    starttime,
    endtime,
    itemid,
    amount,
    amountuom,
    totalamount,
    totalamountuom,
    statusdescription
  )

db_mg_input_events |>
  count(statusdescription, sort = TRUE) |>
  collect()

FinishedRunning、Stopped、Paused、ChangeDose/Rate のような値は、投与が終了・停止・一時停止・速度変更されたことを示すため、通常は投与イベントとして扱えます。
念のため、これらの行に実際の投与量が記録されているかを、amount、totalamount、欠測数で確認します。

db_mg_input_events |>
  group_by(statusdescription) |>
  summarise(
    n = n(),
    n_amount_pos = sum(if_else(!is.na(amount) & amount > 0, 1L, 0L)),
    n_totalamount_pos = sum(if_else(!is.na(totalamount) & totalamount > 0, 1L, 0L)),
    n_amount_missing = sum(if_else(is.na(amount), 1L, 0L)),
    .groups = "drop"
  )

ICU入室前に開始されたMg投与を抽出します。
inputevents はICU内の投与記録ですが、starttime が icu_intime より前の場合、ICU入室前からMg投与が開始されていた可能性があります。

db_mgso4_before_icu_input <-
  db_bja_step02_no_high_mg |>
  select(
    subject_id,
    hadm_id,
    stay_id,
    icu_intime
  ) |>
  inner_join(
    db_mg_input_events,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  filter(
    starttime < icu_intime,
    is.na(statusdescription) |
      !str_detect(
        str_to_lower(statusdescription),
        "rewritten|canceled|cancelled"
      )
  )

db_mgso4_before_icu_input |>
  summarise(
    n_rows = n(),
    n_stays_with_mgso4_before_icu_input = n_distinct(stay_id)
  )

ここでは prescriptions はICU入室前投与の除外にも使いません。
処方オーダーだけでICU入室前に実投与があったと判断すると、実際には投与されていない患者まで除外する可能性があるためです。
この演習では、主定義と同じく emar と inputevents で確認できる投与記録を使って、ICU入室前MgSO4投与があった患者をまとめます。

db_mgso4_before_icu_emar_stays <-
  db_mgso4_before_icu_emar |>
  distinct(subject_id, hadm_id, stay_id) |>
  mutate(src_emar_before_icu = 1L) |> 
  compute()

db_mgso4_before_icu_input_stays <-
  db_mgso4_before_icu_input |>
  distinct(subject_id, hadm_id, stay_id) |>
  mutate(src_input_before_icu = 1L) |> 
  compute()

db_mgso4_before_icu_exclusion <-
  db_bja_step02_no_high_mg |>
  select(subject_id, hadm_id, stay_id) |>
  left_join(
    db_mgso4_before_icu_emar_stays,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  left_join(
    db_mgso4_before_icu_input_stays,
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  mutate(
    src_emar_before_icu = coalesce(src_emar_before_icu, 0L),
    src_input_before_icu = coalesce(src_input_before_icu, 0L),
    mgso4_before_icu = if_else(
      src_emar_before_icu == 1L |
        src_input_before_icu == 1L,
      1L,
      0L
    )
  ) |> 
  compute()

db_mgso4_before_icu_exclusion |>
  count(
    src_emar_before_icu,
    src_input_before_icu
  )
db_mgso4_before_icu_exclusion |>
  count(mgso4_before_icu)

患者データに結合し、ICU入室前MgSO4投与例を除外します。

db_bja_step02_patients <-
  db_bja_step02_no_high_mg |>
  left_join(
    db_mgso4_before_icu_exclusion |>
      select(
        subject_id,
        hadm_id,
        stay_id,
        src_emar_before_icu,
        src_input_before_icu,
        mgso4_before_icu
      ),
    by = c("subject_id", "hadm_id", "stay_id")
  ) |>
  mutate(
    src_emar_before_icu = coalesce(src_emar_before_icu, 0L),
    src_input_before_icu = coalesce(src_input_before_icu, 0L),
    mgso4_before_icu = coalesce(mgso4_before_icu, 0L)
  ) |>
  filter(mgso4_before_icu == 0L)

db_bja_step02_patients |>
  summarise(
    n_rows = n(),
    n_stays = n_distinct(stay_id),
    n_subjects = n_distinct(subject_id)
  )

第2回講義

主要評価項目:28日全死亡

BJA論文の主要評価項目は28日全死亡です。
論文本文では28日の起点が明示されていないため、敗血症研究としてより自然な解釈である sepsis_onset_time を起点として28日以内の死亡を作成します。 ここで用いる sepsis_onset_time は、感染疑いとSOFA基準の両方がそろった時点です。

起点による判定の違いを確認するため、ICU入室日を起点とした28日全死亡もdeath_28d_icu_startとして作成します。

dod は患者の死亡日です。
dod は日付であり、時刻情報を持たないため、ここでは sepsis_onset_time と icu_intime も日付に変換して差を取ります。

この段階では患者数が十分に小さくなっているため、いったん collect() してインメモリで処理します。

df_bja_step02_patients <-
  db_bja_step02_patients |>
  collect()

df_bja_step02_po <-
  df_bja_step02_patients |>
  mutate(
    icu_intime_date = as.Date(icu_intime),
    sepsis_onset_date = as.Date(sepsis_onset_time),
    dod_date = as.Date(dod),

    days_to_death_icu_start = as.numeric(dod_date - icu_intime_date),
    death_28d_icu_start = if_else(
      !is.na(days_to_death_icu_start) &
        days_to_death_icu_start >= 0 &
        days_to_death_icu_start <= 28,
      1L,
      0L
    ),
    followup_days_28d_icu_start = if_else(
      death_28d_icu_start == 1L,
      days_to_death_icu_start,
      28
    ),

    days_to_death = as.numeric(dod_date - sepsis_onset_date),
    death_28d = if_else(
      !is.na(days_to_death) & days_to_death >= 0 & days_to_death <= 28,
      1L,
      0L
    ),
    followup_days_28d = if_else(
      death_28d == 1L,
      days_to_death,
      28
    )
  )

df_bja_step02_po |>
  count(death_28d)

ICU入室起点の旧定義と、sepsis onset起点の主定義がどの程度異なるかも確認します。

df_bja_step02_po |>
  count(death_28d_icu_start, death_28d)

院内死亡フラグもあわせて確認します。

df_bja_step02_po |>
  count(hospital_expire_flag, death_28d)

Table 1の練習

ここでは全体の患者背景を確認します。
連続値やカテゴリ変数は、Table 1を作る前に必ず分布と欠測を確認します。

この第2回では、Table 1を作る練習として、race、admission_type、insurance などを元のデータに近い形のまま使用します。
BJA論文のTable 1に近づけるための race の再分類、ICU typeの分類、Mg statusの整理などは、第3回でExposureと共変量を作成するときに行います。

df_bja_step02_po |>
  select(
    age,
    gender,
    race,
    admission_type,
    insurance,
    icu_stay_hours,
    sofa_score,
    death_28d
  ) |>
  skimr::skim()
Data summary
Name select(…)
Number of rows 11755
Number of columns 8
_______________________
Column type frequency:
character 4
numeric 4
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
gender 0 1.00 1 1 0 2 0
race 0 1.00 5 41 0 33 0
admission_type 0 1.00 6 27 0 9 0
insurance 233 0.98 5 8 0 4 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
age 0 1 65.10 16.62 18.00 55.00 67.00 78.00 91.00 ▁▂▆▇▆
icu_stay_hours 0 1 141.61 164.04 24.01 46.84 82.08 168.82 2441.43 ▇▁▁▁▁
sofa_score 0 1 3.61 2.00 2.00 2.00 3.00 4.00 17.00 ▇▁▁▁▁
death_28d 0 1 0.18 0.39 0.00 0.00 0.00 0.00 1.00 ▇▁▁▁▂

Table 1に入れる変数を指定します。

continuous <- c("age", "icu_stay_hours", "sofa_score")
factors <- c("gender", "race", "admission_type", "insurance", "death_28d")

連続値は、Table 1を作る前に必ずヒストグラムで分布を確認します。 外れ値や極端に偏った分布がある場合、平均と標準偏差だけではデータの特徴を見落とす可能性があるためです。

df_bja_step02_po |>
  select(all_of(continuous)) |>
  pivot_longer(
    cols = all_of(continuous),
    names_to = "name",
    values_to = "value"
  ) |>
  ggplot() +
  geom_histogram(aes(x = value), color = "black", fill = "grey80") +
  facet_wrap(~ name, scales = "free", ncol = 2) +
  theme_bw()

df_tableone_step02 <-
  df_bja_step02_po |>
  select(all_of(c(continuous, factors)))

tableone_step02 <-
  tableone::CreateTableOne(
    vars = c(continuous, factors),
    data = df_tableone_step02,
    factorVars = factors
  )

print(tableone_step02, smd = TRUE, missing = TRUE)
##                                               
##                                                Overall         Missing
##   n                                             11755                 
##   age (mean (SD))                               65.10 (16.62)  0.0    
##   icu_stay_hours (mean (SD))                   141.61 (164.04) 0.0    
##   sofa_score (mean (SD))                         3.61 (2.00)   0.0    
##   gender = M (%)                                 6873 (58.5)   0.0    
##   race (%)                                                     0.0    
##      AMERICAN INDIAN/ALASKA NATIVE                 22 ( 0.2)          
##      ASIAN                                        137 ( 1.2)          
##      ASIAN - ASIAN INDIAN                          24 ( 0.2)          
##      ASIAN - CHINESE                               97 ( 0.8)          
##      ASIAN - KOREAN                                14 ( 0.1)          
##      ASIAN - SOUTH EAST ASIAN                      33 ( 0.3)          
##      BLACK/AFRICAN                                 27 ( 0.2)          
##      BLACK/AFRICAN AMERICAN                       729 ( 6.2)          
##      BLACK/CAPE VERDEAN                            63 ( 0.5)          
##      BLACK/CARIBBEAN ISLAND                        52 ( 0.4)          
##      HISPANIC OR LATINO                           129 ( 1.1)          
##      HISPANIC/LATINO - CENTRAL AMERICAN            10 ( 0.1)          
##      HISPANIC/LATINO - COLUMBIAN                    9 ( 0.1)          
##      HISPANIC/LATINO - CUBAN                        5 ( 0.0)          
##      HISPANIC/LATINO - DOMINICAN                   65 ( 0.6)          
##      HISPANIC/LATINO - GUATEMALAN                  23 ( 0.2)          
##      HISPANIC/LATINO - HONDURAN                     6 ( 0.1)          
##      HISPANIC/LATINO - MEXICAN                     13 ( 0.1)          
##      HISPANIC/LATINO - PUERTO RICAN               125 ( 1.1)          
##      HISPANIC/LATINO - SALVADORAN                  12 ( 0.1)          
##      MULTIPLE RACE/ETHNICITY                       18 ( 0.2)          
##      NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER     21 ( 0.2)          
##      OTHER                                        402 ( 3.4)          
##      PATIENT DECLINED TO ANSWER                    78 ( 0.7)          
##      PORTUGUESE                                    49 ( 0.4)          
##      SOUTH AMERICAN                                 7 ( 0.1)          
##      UNABLE TO OBTAIN                             243 ( 2.1)          
##      UNKNOWN                                     1586 (13.5)          
##      WHITE                                       7436 (63.3)          
##      WHITE - BRAZILIAN                             20 ( 0.2)          
##      WHITE - EASTERN EUROPEAN                      34 ( 0.3)          
##      WHITE - OTHER EUROPEAN                       192 ( 1.6)          
##      WHITE - RUSSIAN                               74 ( 0.6)          
##   admission_type (%)                                           0.0    
##      AMBULATORY OBSERVATION                         1 ( 0.0)          
##      DIRECT EMER.                                 509 ( 4.3)          
##      DIRECT OBSERVATION                             4 ( 0.0)          
##      ELECTIVE                                     461 ( 3.9)          
##      EU OBSERVATION                                 2 ( 0.0)          
##      EW EMER.                                    5894 (50.1)          
##      OBSERVATION ADMIT                           1087 ( 9.2)          
##      SURGICAL SAME DAY ADMISSION                  627 ( 5.3)          
##      URGENT                                      3170 (27.0)          
##   insurance (%)                                                2.0    
##      Medicaid                                    1623 (14.1)          
##      Medicare                                    6553 (56.9)          
##      Other                                        339 ( 2.9)          
##      Private                                     3007 (26.1)          
##   death_28d = 1 (%)                              2147 (18.3)   0.0

データベース上に保存する

第2回の完成データを bja_step02_po_2026 とします。
PとO、すなわち対象患者と主要評価項目まで作成済みのデータです。
第3回では、このデータにExposureと共変量を追加していきます。

注意: 同じ名前のテーブルが既に存在する場合は、いったん既存テーブルを削除してから、新しく作成し直します。
したがって、このコードを実行すると、既存のテーブルは置き換えられます。
過去の結果を残したい場合は、output_table を別名に変更してください。

output_table <- "bja_step02_po_2026"

if (DBI::dbExistsTable(con_mimic, output_table)) {
  DBI::dbRemoveTable(con_mimic, output_table)
}

DBI::dbWriteTable(
  conn = con_mimic,
  name = output_table,
  value = df_bja_step02_po
)

保存処理を実行した場合は、以下でテーブル一覧を確認します。

DBI::dbListTables(con_mimic)
##  [1] "admissions"                     "antibiotic"                    
##  [3] "apsiii"                         "bja_step01_patients_2026"      
##  [5] "bja_step02_po_2026"             "bja_step03_analysis_base_2026" 
##  [7] "caregiver"                      "charlson"                      
##  [9] "chartevents"                    "crrt"                          
## [11] "d_hcpcs"                        "d_icd_diagnoses"               
## [13] "d_icd_procedures"               "d_items"                       
## [15] "d_labitems"                     "datetimeevents"                
## [17] "dbplyr_45Hf8WFB9S"              "dbplyr_CGwkbIEtYY"             
## [19] "dbplyr_DXiGe7clVX"              "dbplyr_GGdj1HDvr5"             
## [21] "dbplyr_YZ8eSDolQu"              "dbplyr_dFWbQht5it"             
## [23] "dbplyr_kYLifuTbwF"              "dbplyr_lyTsGdBvrd"             
## [25] "diagnoses_icd"                  "dobutamine"                    
## [27] "dopamine"                       "drgcodes"                      
## [29] "emar"                           "emar_detail"                   
## [31] "epinephrine"                    "first_day_gcs"                 
## [33] "first_day_height"               "first_day_lab"                 
## [35] "first_day_rrt"                  "first_day_sofa"                
## [37] "first_day_urine_output"         "first_day_vitalsign"           
## [39] "first_day_weight"               "hcpcsevents"                   
## [41] "height"                         "icustay_detail"                
## [43] "icustays"                       "ingredientevents"              
## [45] "inputevents"                    "kdigo_creatinine"              
## [47] "kdigo_stages"                   "kdigo_uo"                      
## [49] "labevents"                      "microbiologyevents"            
## [51] "norepinephrine"                 "norepinephrine_equivalent_dose"
## [53] "oasis"                          "omr"                           
## [55] "outputevents"                   "patients"                      
## [57] "pharmacy"                       "phenylephrine"                 
## [59] "poe"                            "poe_detail"                    
## [61] "prescriptions"                  "procedureevents"               
## [63] "procedures_icd"                 "provider"                      
## [65] "rrt"                            "sapsii"                        
## [67] "sepsis3"                        "services"                      
## [69] "sofa"                           "transfers"                     
## [71] "vasoactive_agent"               "vasopressin"                   
## [73] "ventilation"                    "weight_durations"

<第2回講義・課題>

第3回では、Exposureと共変量を作成します。
その準備として、以下を行ってください。

  1. derivedファイルを入手する
    第3回で直接使うため、まず以下12個のderivedファイルをBigQueryから取得し、ローカルのderivedフォルダに保存してください。
    sepsis3、sofa、sapsii、charlson、antibiotic、ventilation、vasoactive_agent、height、first_day_height、first_day_weight、weight_durations、first_day_vitalsign

余裕がある場合、またはderivedデータをより広く確認したい場合は、以下32個を取得しても構いません。第3回の主な演習は、上記12個があれば進められます。
sepsis3、antibiotic、charlson、apsiii、oasis、sapsii、first_day_sofa、sofa、icustay_detail、first_day_lab、first_day_vitalsign、first_day_gcs、height、first_day_height、weight_durations、first_day_weight、first_day_urine_output、first_day_rrt、ventilation、vasoactive_agent、rrt、crrt、norepinephrine_equivalent_dose、norepinephrine、epinephrine、dopamine、dobutamine、vasopressin、phenylephrine、kdigo_stages、kdigo_creatinine、kdigo_uo

  1. Exposureのフラグ立てを行う
    MgSO4投与あり/なしを示す mgso4_exposure、初回投与時刻を示す first_mgso4_time を作成してください。
    ヒント: emar と inputevents からMgSO4投与を拾い、Sepsis onset以後の最初の時刻を患者ごとにまとめます。

  2. 共変量を取得する
    第4回では、第3回で作成したTable 1に近い共変量を用いて、MICEとPSMを行います。
    そのため、第3回では、患者背景、重症度、治療、併存疾患、バイタルサイン、Sepsis onset近傍の検査値を取得します。
    年齢、性別、人種、ICU type、入院年、BMI、SOFA、SAPS II、Charlson comorbidity index、Mg status、抗菌薬投与、人工呼吸、昇圧薬、K補充、Ca補充、併存疾患、バイタルサイン、白血球数、血小板数、血糖、Hb、Mg、K、Na、Ca、Cl、リンを取得できるように準備してください。

# DBI::dbDisconnect(con_mimic, shutdown = TRUE)

END