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

如何用summarise_at按MRN和日期返回对应最小差值的BMI3值

Solution: Get BMI3 Corresponding to Minimum BMI3_mode_diff_abs per Group

To retrieve the BMI3 value associated with the smallest BMI3_mode_diff_abs for each combination of MRN and OBSERVATION_DATE, use one of these dplyr-based approaches:

Approach 1: Concise Selection with slice_min

This method directly picks the row with the minimum difference per group and extracts the corresponding BMI3 value:

library(dplyr)

BMI_same_day <- BMIdf %>%
  group_by(MRN, OBSERVATION_DATE) %>%
  slice_min(BMI3_mode_diff_abs, na.rm = TRUE, with_ties = FALSE) %>%
  select(MRN, OBSERVATION_DATE, BMI3) %>%
  rename(BMI_same_day = BMI3) %>%
  ungroup()
  • slice_min(..., na.rm = TRUE) ignores NA values when calculating the minimum difference.
  • with_ties = FALSE selects only the first row if multiple rows share the same minimum difference (set to TRUE to keep all tied rows).
  • ungroup() removes the grouping structure after processing.

Approach 2: Preserve All Groups with summarise

This method matches your original code's behavior by retaining every group—including those where all BMI3_mode_diff_abs values are NA (returning NA for BMI_same_day in those cases):

library(dplyr)

BMI_same_day <- BMIdf %>%
  group_by(MRN, OBSERVATION_DATE) %>%
  summarise(
    BMI_same_day = case_when(
      all(is.na(BMI3_mode_diff_abs)) ~ NA_real_,
      TRUE ~ BMI3[which.min(BMI3_mode_diff_abs)]
    ),
    .groups = "drop"
  )
  • case_when first checks if all differences are NA, returning NA if true.
  • which.min(BMI3_mode_diff_abs) finds the index of the smallest non-NA difference, then pulls the corresponding BMI3 value.
  • .groups = "drop" cleans up the grouping structure after summarization.

Key Difference

Approach 1 drops groups where all BMI3_mode_diff_abs values are NA, while Approach 2 keeps these groups with an NA BMI_same_day value—matching the output structure of your original code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:54:55