Home > Net >  Given a list of nested tibbles how do I map function to each object?
Given a list of nested tibbles how do I map function to each object?

Time:09-02

I have a list of nested tibbles (which includes lists themselves etc, sort of like inception).

library(tidyverse)

# example function I want to apply
fun1 <- function(data) {
  minimum <- min(data$Sepal.Length)

  return(minimum)
}


# example of nested list
list_nested_tibbles <- list(
  list1 = iris %>% group_by(Species) %>% nest(),
  list2 = iris %>% group_by(Species) %>% nest()
)


# applying function to one of the nested tibbles within the list
list_nested_tibbles$list1 %>% mutate(minimum = map_dbl(.x = data, ~ fun1(.x)))
#> # A tibble: 3 x 3
#> # Groups:   Species [3]
#>   Species    data              minimum
#>   <fct>      <list>              <dbl>
#> 1 setosa     <tibble [50 x 4]>     4.3
#> 2 versicolor <tibble [50 x 4]>     4.9
#> 3 virginica  <tibble [50 x 4]>     4.9

# function fails if I apply across whole list
list_nested_tibbles %>% mutate(minimum = map_dbl(.x = data, ~ fun1(.x)))
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "list"

However, I want to apply the function to both list items simultaneously, I'm guessing I need some sort of nested map statement?

Any help appreciated.

Cheers.

CodePudding user response:

Here's how to do it with purrr functions:

map(list_nested_tibbles, ~ .x %>% mutate(minimum = map_dbl(data, ~ fun1(.x))))
$list1
# A tibble: 3 × 3
# Groups:   Species [3]
  Species    data              minimum
  <fct>      <list>              <dbl>
1 setosa     <tibble [50 × 4]>     4.3
2 versicolor <tibble [50 × 4]>     4.9
3 virginica  <tibble [50 × 4]>     4.9

$list2
# A tibble: 3 × 3
# Groups:   Species [3]
  Species    data              minimum
  <fct>      <list>              <dbl>
1 setosa     <tibble [50 × 4]>     4.3
2 versicolor <tibble [50 × 4]>     4.9
3 virginica  <tibble [50 × 4]>     4.9
  • Related