Skip to content

print and execute functions in a package namespace

2 messages · Michael Friendly, Hadley Wickham

#
Let's say I have a package that consists of a set of functions, fig1(), 
fig2(), fig3() ..., each of which
produces a plot, and perhaps some printed output,  e.g.,

fig1 <- function() plot(1:10)
fig2 <- function() plot(10:1)
fig3 <- function() {y<-sample(1:10,10); plot(y); y}

I'd like to produce a document (PDF or HTML) containing the listing of 
each function and its output,
using knittr.

I can execute a list of figures using something like

# print and run a figure function
onefig <- function(fig) {
     cat("Figure:") # how to get name of fig function?
     print(fig)
     fig()
}

lapply(list(fig1, fig2, fig3), onefig)

But I need to work with the names of the figure functions instead, 
something like

figlist <- paste0("fig", 1:3)

# using figure name
onefig2 <- function(fig) {
     cat("Figure:", fig, "\n")
     print(body(fig))
     eval(parse((paste0(fig,'()'))))   # doesn't work
}

As well, I need to be able to find all functions in the package 
namespace matching a pattern.
Can someone help?
#
Are the functions exported or internal?

# Use for internal functions
pkg <- asNamespace("mypackage")
# Use for exported functions:
pkg <- "package:mypackage"

# Find functions matching a pattern:
figfuns <- grep("fun.*", ls(pkg), value = TRUE)

# Convert names into functions
funs <- lapply(fig, get, envir = pkg)

onefig2 <- function(fig) {
    cat("Figure:", fig, "\n")
    print(body(fig))
    fig()
}
lapply(funs, onefig2)

Hadley