Search code examples
rlistfurrr

Map a function to a specific element of all sub-lists within a list conditionally - R


Task:

  • I would like to apply a function conditionally with ifelse to a specific element across all sub-lists within a named list in R.
  • I would like to store this output in a named list.
  • Additionally, how can I extract the elements in the sub-lists where the condition is met and store in a new named list?

The list is of ggplot2 plots.

Data:

library(furrr)
library(data.table)

my_list <- list(ggplot_1 = ggplot_1, ggplot_2 = ggplot_2, ggplot_3 = ggplot_3)
my_names <- names(my_list)

str(my_list)
> list of 3
>  $ggplot_1 : list of 9
>   $data :'data.frame': 20 obs. of 10 variables:
    # Other sub-list elements...
>
>  $ggplot_2 : list of 9
>   $data :'data.frame': 0 obs. of 10 variables:
    # Other sub-list elements...
>
>  $ggplot_3 : list of 9
>   $data :'data.frame': 10 obs. of 10 variables:
    # Other sub-list elements...

On its own the following works:

ifelse(nrow(my_list$ggplot_1$data) != 0, TRUE, FALSE)
> TRUE
ifelse(nrow(my_list$ggplot_2$data) != 0, TRUE, FALSE)
> FALSE

Attempt:

# I have used mapping functions from the furrr package, 
# but this approach should be similar (although sequential) for purrr::map2/base::Map.

# Start multisession parallel backend
plan(multisession, workers = 2)

# Attempt to map a function conditionally through a list
future_map2(my_list, my_names, function(.x, .y) {
            ifelse(nrow(.x$.y$data) != 0, TRUE, FALSE))
  })

Solution

  • We can use keep to filter the list elements`

    purrr::keep(my_list, ~ nrow(.x$data) > 0)
    

    Or using base R with Filter

    Filter(function(x) nrow(x$data) > 0, my_list)