首页 > 解决方案 > 如何列出在函数中调用的所有用户定义函数或在 R 中使用 pryr 包的用户定义函数?

问题描述

基本上我需要找出功能列表/用户定义的功能树图有用功能的层次结构并将它们跟踪到最后一片叶子以了解其背后的业务逻辑并在可能的情况下对其进行重新编码。

最近我发布了一个类似的问题并被指示检查pryr包上的帖子:如何列出在函数中调用的所有用户定义函数或 R 中的用户定义函数?

问题:当我执行时,call_tree(parse(text=user_defined_function()))我得到一个错误,因为之前的帖子被标记为重复太快,我不能在那里问。

我的尝试:( 虚拟数据)


library(tidyverse)
library(lubridate)
library(pryr)

test_df <- data.frame(id = c(1234, 1234, 5678, 5678),
           date = c("2021-10-10","2021-10-10", "2021-8-10", "2021-8-15"),
           Amount  = c(54767, 96896, 34534, 79870),
           type = c("lt","mt","mt","mt")) %>% 
  
  mutate(date = ymd(date))
plt_test_df <- function(type_value = "mt"){
  test_df %>% 
  filter(type == type_value) %>% 
  
  ggplot(aes(x = date, y = Amount)) +
  geom_line(alpha = 0.5, show.legend = FALSE, size = 0.8) +
  geom_point()
}

当我尝试跟踪此函数时,出现错误:

trace_func_depth <- capture.output(pryr::call_tree(parse(text = plt_test_df())))

错误:

Error in parse(text = plt_test_df()) : <text>:2:6: unexpected '<'
1: list(id = c(1234, 5678, 5678), date = c(18910, 18849, 18854), Amount = c(96896, 34534, 79870), type = c("mt", "mt", "mt"))
2: list(<
^

如果这不适用于用户定义的函数名称,那么这将在跟踪那些用户定义的函数以及在用户定义的函数本身中调用的函数中起作用吗?

是否有任何库可以为用户定义的函数构建树级结构并深入跟踪使用 in 调用的所有用户定义的函数。我不确定这是否pryr可以做到这一点。

这似乎只在我传递完整函数而不是函数名时才有效:

trace_func_depth <- capture.output(pryr::call_tree(parse(text = "test_df %>% 
  filter(type == 'mt') %>% 
  
  ggplot(aes(x = date, y = Amount)) +
  geom_line(alpha = 0.5, show.legend = FALSE, size = 0.8) +
  geom_point()")))

trace_func_depth
[1] "\\- ()"                  "  \\- `+"                "  \\- ()"               
 [4] "    \\- `+"              "    \\- ()"              "      \\- `%>%"         
 [7] "      \\- ()"            "        \\- `%>%"        "        \\- `test_df"   
[10] "        \\- ()"          "          \\- `filter"   "          \\- ()"       
[13] "            \\- `=="     "            \\- `type"   "            \\-  \"mt\""
[16] "      \\- ()"            "        \\- `ggplot"     "        \\- ()"         
[19] "          \\- `aes"      "          \\- `date"     "          \\- `Amount"  
[22] "    \\- ()"              "      \\- `geom_line"    "      \\-  0.5"         
[25] "      \\-  FALSE"        "      \\-  0.8"          "  \\- ()"               
[28] "    \\- `geom_point " 

标签: r

解决方案


推荐阅读