Group_by on elements of a large list

Are you looking for something like the following. If not, please post an example of your data as a Reproducible Example.

library(purrr)
#> Warning: package 'purrr' was built under R version 3.5.3
library(dplyr)

LIST <- list(A = data.frame(D = 1:6, B = rep(LETTERS[1:3], 2)),
             C = data.frame(E = 2:7, B = rep(LETTERS[1:3], 2)))
LIST
#> $A
#>   D B
#> 1 1 A
#> 2 2 B
#> 3 3 C
#> 4 4 A
#> 5 5 B
#> 6 6 C
#> 
#> $C
#>   E B
#> 1 2 A
#> 2 3 B
#> 3 4 C
#> 4 5 A
#> 5 6 B
#> 6 7 C

MyFunc <- function(DF) {
  DF %>% group_by(B) %>% 
    mutate(NewCol = 1:n()) %>%
    arrange(B)
}

LIST2 <- map(LIST, MyFunc)
LIST2
#> $A
#> # A tibble: 6 x 3
#> # Groups:   B [3]
#>       D B     NewCol
#>   <int> <fct>  <int>
#> 1     1 A          1
#> 2     4 A          2
#> 3     2 B          1
#> 4     5 B          2
#> 5     3 C          1
#> 6     6 C          2
#> 
#> $C
#> # A tibble: 6 x 3
#> # Groups:   B [3]
#>       E B     NewCol
#>   <int> <fct>  <int>
#> 1     2 A          1
#> 2     5 A          2
#> 3     3 B          1
#> 4     6 B          2
#> 5     4 C          1
#> 6     7 C          2

Created on 2019-09-16 by the reprex package (v0.2.1)

2 Likes