How do I apply a function to a list of tibbles?

Using the group_split function on a data frame I've ended up with a list of 18 Tibbles. I now wish to take the top 30 rows of each of these new tibbles, However simply calling the list and using top(list, 30), does not work.

I've noted that calling out individual tibbles within the list does work i.e. top(list[[1]], 30).

I'm pretty inept at using r, so any help would be great!

my go to for this sort of thing would be a map function from purrr package

1 Like

As @nirgrahamuk said, map is the way to go. Here's a toy example where I'm selecting the top row of each tibble from a list of 3. You can adapt this to your own data.

library(tidyverse)

tbl <- tibble(Fruit = rep(c("Apple", "Mango", "Banana"), 3),
              Quantity = seq(1:9))

print(tbl)
#> # A tibble: 9 x 2
#>   Fruit  Quantity
#>   <chr>     <int>
#> 1 Apple         1
#> 2 Mango         2
#> 3 Banana        3
#> 4 Apple         4
#> 5 Mango         5
#> 6 Banana        6
#> 7 Apple         7
#> 8 Mango         8
#> 9 Banana        9

tbl %>% 
  group_split(Fruit) %>% 
  map(slice, 1L)
#> [[1]]
#> # A tibble: 1 x 2
#>   Fruit Quantity
#>   <chr>    <int>
#> 1 Apple        1
#> 
#> [[2]]
#> # A tibble: 1 x 2
#>   Fruit  Quantity
#>   <chr>     <int>
#> 1 Banana        3
#> 
#> [[3]]
#> # A tibble: 1 x 2
#>   Fruit Quantity
#>   <chr>    <int>
#> 1 Mango        2

Created on 2020-02-21 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.