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

373 Views Asked by At

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))
  })
2

There are 2 best solutions below

3
On BEST ANSWER

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)
1
On

You don't need map2 as the names are already in the list you want to map.
ifelse is also not necessary as > operator already returns a boolean.

library(purrr)
library(ggplot2)

my_list %>% map(~nrow(.x$data)!=0)


$ggplot_1
[1] TRUE

$ggplot_2
[1] TRUE

$ggplot_3
[1] FALSE

The above example works with purrr, and you just need to replace map by future_map to transpose it to furrr.