如何用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 = FALSEselects only the first row if multiple rows share the same minimum difference (set toTRUEto 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_whenfirst 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 correspondingBMI3value..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
相关产品推荐
相关产品推荐

