任务:
- 我想有条件地将函数应用于R中
ifelse
命名的所有子列表中的特定元素。list
- 我想将此输出存储在一个名为
list
. - 此外,如何提取满足条件的子列表中的元素并将其存储在新的命名列表中?
清单是 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))
})