Adding help docs to user-defined functions


#1

Is it possible to add help to functions defined (with assign) inside an R session?

Let's say I define a set of functions like so:

make_addn <- function(n) {                        
  function(x) x + n                                 
}                                                 
                                                  
assign_addn <- function(n, env) {                 
  name <- paste0("add", n)                          
  fn <- make_addn(n)                                
  assign(name, fn, envir = env)                     
}                                                 
                                                  
purrr::walk(2:5, assign_addn, env = environment())
                                                  
add2(3)                                           
#> [1] 5
add5(5)                                           
#> [1] 10
                                                  
help(add3)                                        
#> No documentation for 'add3' in specified packages and libraries:
#> you could try '??add3'

What I want to add is something like:

assign_addn <- function(n, env) {                 
  name <- paste0("add", n)                          
  fn <- make_addn(n)                
  help_text <- glue::glue("Add {n} to a number")                

  # make help text??
  assign(name, fn, envir = env)                     
}  

# ...

help(add3) 
#> Add 3 to a number

Does this make sense? Is this possible? Or even desirable?


#2

AFAIK this is only possible if you make a package of your function, but that doesn't need to be a show stopper.

I have an internal personal package that I quickly add utility functions to - you hit Build in one RStudio window, restart the R session in your work flow, reload the utility package then you are done. The new function is available in all R sessions, complete with documentation, examples, testing etc.

If you haven't made a package before don't be put off, since if you are making functions now its not a big leap, basically adding a lot of standard files, and following this guide helped me heaps.


#3

Thank you, Marke. What I'm primarily concerned with here is adding documentation for new functions, specifically functions created by other functions, in which case packaging isn't a solution.

For instance, if I have a package that allows a user to define a set of functions programatically (like the add* functions in the (admittedly twee) example), can documentation be defined alongside the functions?

Eyeballing the help function's source code, it seems like it might be possible to create some documentation in a temporary file and append the path to .libPaths() for the current R session? Or maybe appending to a more specific path used to search for documentation?

Intuitively, this seems like bad practice and that it might have unintented consequences. Still, I'm curious to see where this goes.