CodexBloom - Programming Q&A Platform

scenarios with `dplyr::summarise()` not retaining group columns when using `across()` in R 4.3

πŸ‘€ Views: 48 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-18
r dplyr data-manipulation R

I've been banging my head against this for hours. Does anyone know how to I've searched everywhere and can't find a clear answer. I'm running into an scenario where using `dplyr::summarise()` with `across()` doesn't seem to retain the grouping variables in my resulting data frame. I have a dataset with several columns, and I'm trying to calculate the mean of some numeric columns while keeping the grouping columns in the final output. However, the resulting data frame only includes the summarised values without the grouping columns. Here’s the code I'm using: ```r library(dplyr) df <- data.frame( group = rep(c('A', 'B'), each = 4), value1 = c(1, 2, 3, 4, 5, 6, 7, 8), value2 = c(10, 20, 30, 40, 50, 60, 70, 80) ) df_summary <- df %>% group_by(group) %>% summarise(across(starts_with('value'), mean)) ``` When I run this code, I expect `df_summary` to return both the `group` and the mean of `value1` and `value2`, but it only returns the means: ``` # A tibble: 2 x 2 value1 value2 <dbl> <dbl> 1 2 25 2 6 65 ``` I've tried using `add_tally()` before summarising to retain the grouping column, but that just adds a count column instead. I also checked the `dplyr` version and it’s 1.1.0. What am I missing? Is there a specific way to retain the grouping columns while still using `across()`? I'd really appreciate any guidance on this. I'm working on a application that needs to handle this. Has anyone else encountered this? The project is a microservice built with R. I'm coming from a different tech stack and learning R. I'd be grateful for any help.