r - 如何将 tribble 转换为列表并转换函数名称?
问题描述
我有一个tbl_df
我创建的样本。我正在寻找创建一个列表,该列表使用list_name
每个列表名称的列,并填写列表以匹配我的example_list
下面。另外,我想转换scrape_func
列中的字符值以存储列表中实际函数的名称。我只mean
在列表中使用作为示例。
样本tbl_df
example_df <-tibble::tribble(
~list_name, ~abbr, ~id, ~scrape_func,
"pepsi", "pep", "pepsi_id", "mean",
"coke", "ck", "coke_id", "mean",
"dr_pepper", "drp", "dr_id", "mean"
)
我正在寻找的列表格式:
example_list <- list(
"pepsi" = list(
list_name = "pepsi",
abbr = "pep",
id = "pepsi_id",
scrape_func = mean
),
"coke" = list(
list_name = "coke",
abbr = "ck",
id = "coke_id",
scrape_func = mean
),
"dr_pepper" = list(
list_name = "dr_pepper",
abbr = "drp",
id = "dr_id",
scrape_func = mean
)
)
如果可能的话,我希望使用解决方案tidyverse
。提前致谢!
解决方案
我们可以使用get
来获取函数的值,并且pmap
可以循环遍历list
library(dplyr)
library(purrr)
out <- example_df %>%
mutate(scrape_func = map(scrape_func, get)) %>%
pmap(c) %>%
set_names(example_df$list_name)
检查预期的输出
all.equal(out, example_list)
#[1] TRUE
或与match.fun
out <- example_df %>%
mutate(scrape_func = map(scrape_func, match.fun)) %>%
pmap(c) %>%
set_names(example_df$list_name)
all.equal(out, example_list)
#[1] TRUE
更新
如果 OP 想要存储为符号,请使用as.symbol
oras.name
或 with rlang::sym
orrlang::syms
out2 <- example_df %>%
mutate(scrape_func = map(scrape_func, as.name)) %>%
pmap(c) %>%
set_names(example_df$list_name)
out2$pepsi$scrape_func
#mean
我们可以用match.fun
match.fun(out2$pepsi$scrape_func)
#function (x, ...)
#UseMethod("mean")
#<bytecode: 0x7ffdc09fef58>
#<environment: namespace:base>
推荐阅读
- java - RecyclerView 项影响 RecyclerView 外的 TextView 的值
- mysql - MariaDB - 我应该向我的表添加索引吗?
- ruby-on-rails - Rails has_many 通过 where 子句
- python - python beautifulsoup select,如何获取特定值
- c++ - 哪一个更适合存储字符,矢量
还是字符串? - powerbi - Power BI - 列数有限的矩阵
- bonjour - 是否可以让 mDNS / Bonjour 在不同的服务器上发布相同的服务名称
- json - 请求 JSON 文件内容的空 GET 响应 | koa2
- java - 访问 WMTS 服务的 Geotools 抛出 stackoverflow 解析 XML
- postgresql - 无法访问在 docker 入口点文件中创建的 postgres 扩展,直到我在 psql 中手动创建它