有条件地将函数映射到列表中所有子列表的特定元素 - R

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

任务:

列表中有ggplot2个地块。

数据:

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...

独立完成以下作品:

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

尝试:

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

您不需要 map2,因为名称已经在您想要的列表中 map
ifelse 也不是必需的,因为 > 运算符已经 returns 一个布尔值。

library(purrr)
library(ggplot2)

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


$ggplot_1
[1] TRUE

$ggplot_2
[1] TRUE

$ggplot_3
[1] FALSE

以上示例适用于purrr,您只需将map替换为future_map即可将其转置为furrr

我们可以使用 keepfilter list 元素`

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

或使用 base RFilter

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