r - 有条件地将函数映射到列表中所有子列表的特定元素 - R
问题描述
任务:
- 我想有条件地将函数应用于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))
})
解决方案
您不需要map2
,因为名称已经在您想要的列表中map
。
ifelse
也不是必需的,因为>
运算符已经返回一个布尔值。
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
。
推荐阅读
- python - 多对多字段上的 Django 唯一
- sql - 将第一个单词提取到第一个空格 - POSTGRES
- discord - How do I add a mention ability when using a command such us "rate @user" discord.js?
- ruby - 如何编写使用 with 发送参数的方法模拟
- c++ - 对 CLSID_FileOpenDialog 的引用不足 - Mingw64
- angular - 如何使用双向绑定以角度同时检查用户名和电子邮件
- python - Python discord bot,等待消息未按预期工作
- datatable - 从另一个表动态生成 Power BI 中的新表
- storybook - 如何在根级别设置故事书 lerna monorepo
- python - 从html重新创建形状文件?