How to get grouped Sum with nest in one step

Viewed 103

I am unable to get grouped sum in one single step using nest but in 2 steps. How can I use map to loop over data column in the output of nest(). Also suggest a way to include the output column in the existing dataframe.

suppressWarnings(library(tidyverse))
tmp_df <- 
  data.frame(group = rep(c(2L, 1L), each = 5), b = rep(c(-1, 1), each = 5)) 

tmp_df1 = tmp_df %>% group_by(group) %>% nest() #step1
map(tmp_df1$data, sum)  #step 2
#> [[1]]
#> [1] -5
#> 
#> [[2]]
#> [1] 5

I know how to get the sum using group_by.

suppressWarnings(library(tidyverse))
tmp_df <- 
  data.frame(group = rep(c(2L, 1L), each = 5), b = rep(c(-1, 1), each = 5)) 

tmp_df %>% 
  group_by(group) %>% 
  summarise(sum = sum(b))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 2 x 2
#>   group   sum
#>   <int> <dbl>
#> 1     1     5
#> 2     2    -5

Created on 2020-08-04 by the reprex package (v0.3.0)

2 Answers

We can use c_across

library(dplyr)
tmp_df %>% 
     nest_by(group) %>%
     mutate(sum = sum(c_across(data)))

-output

# A tibble: 2 x 3
# Rowwise:  group
#  group               data   sum
#  <int> <list<tbl_df[,1]>> <dbl>
#1     1            [5 × 1]     5
#2     2            [5 × 1]    -5

Or just

tmp_df %>%
   nest_by(group) %>%
   mutate(sum = sum(data))

If you want to use nest you can try map_dbl :

library(tidyverse)

tmp_df %>% 
  group_by(group) %>% 
  nest() %>%
  mutate(sum = map_dbl(data, ~.x %>% sum))

#  group data               sum
#  <int> <list>           <dbl>
#1     2 <tibble [5 × 1]>    -5
#2     1 <tibble [5 × 1]>     5
Related