Michael Friendly
2012-Oct-30 13:37 UTC
[R] print and execute functions in a package namespace
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? -- Michael Friendly Email: friendly AT yorku DOT ca Professor, Psychology Dept. York University Voice: 416 736-2100 x66249 Fax: 416 736-5814 4700 Keele Street Web: http://www.datavis.ca Toronto, ONT M3J 1P3 CANADA
Hadley Wickham
2012-Oct-30 13:52 UTC
[R] print and execute functions in a package namespace
> But I need to work with the names of the figure functions instead, something > like > > figlist <- paste0("fig", 1:3)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 -- RStudio / Rice University http://had.co.nz/