首页 > 解决方案 > 如何将 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。提前致谢!

标签: rlistdplyrpurrr

解决方案


我们可以使用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.symboloras.name或 with rlang::symorrlang::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>

推荐阅读