Snippets

Dénes Türei Search in the code of all loaded R packages

Created by Dénes Türei
library(magrittr)
library(purrr)
library(stringr)
library(methods)
library(dplyr)
library(tibble)


CODE_SAMPLE <- '<add here the code of interest>'

loaded_methods <<-
  getGenerics()@package %>%
  tibble(pkg = ., generic = names(.)) %>%
  mutate(method = map(generic, findMethods)) %>%
  mutate(
    method = map(
      method,
      ~set_names(
          map(.x@.Data, \(x) {x@.Data}),
          .x@names
      )
    )
  ) %>%
  unnest_longer(method, values_to = 'code', indices_to = 'signature')


loaded_functions <<-
  loadedNamespaces() %>%
  set_names(.,.) %>%
  map(asNamespace) %>%
  map(~ls(.x, all.names = TRUE) %>% mget(envir = .x, ifnotfound = NA))


loaded_code <<-
  loaded_methods %>%
  mutate(met_sig = sprintf('%s.%s', generic, signature)) %>%
  group_by(pkg) %>%
  summarize(code = list(set_names(code, met_sig))) %>%
  {set_names(.$code, .$pkg)} %>%
  {map(
    union(names(.), names(loaded_functions)) %>% set_names(.,.),
    function(n) {c(.[[n]], loaded_functions[[n]])}
  )} %>%
  map(~map2(.x, names(.x), ~list(
    obj = .x,
    code = deparse(.x),
    found = str_detect(
      paste(deparse(.x) %>% c(.y), collapse = '\r\n'),
      CODE_SAMPLE
    )
  )))


code_search_result <<-
  loaded_code %>%
  map(~keep(.x, ~extract2(., 'found'))) %>%
  keep(~length(.x) > 0)

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.