Manfredo
Manfredo

Reputation: 1740

R List functions in file

How do I list all functions of a certain R file doing something like

list = list.all.functions(file.name, alphabetical = TRUE, ...)

where list is a string vector containing the names of the functions in file.name?

The solution of How to list all the functions and their arguments in an R file? gives no output for me (since I am not interested in arguments I opened a new question).

EDIT

File allometry.R starts with

#==========================================================================================#
#==========================================================================================#
#    Standing volume of a tree.                                                            #
#------------------------------------------------------------------------------------------#
dbh2vol <<- function(hgt,dbh,ipft){
   vol  = pft$b1Vol[ipft] * hgt * dbh ^ pft$b2Vol[ipft]
   return(vol)
}#end function dbh2ca
#==========================================================================================#
#==========================================================================================#

My main looks like

rm(list=ls())

here     = "/directory/of/allometry.R/"
setwd(here)

is_function = function (expr) {
  if (! is_assign(expr))
    return(FALSE)
  value = expr[[3]]
  is.call(value) && as.character(value[[1]]) == 'function'
}

function_name = function (expr)
  as.character(expr[[2]])

is_assign = function (expr)
  is.call(expr) && as.character(expr[[1]]) %in% c('=', '<-', 'assign')


file_parsed = parse("allometry.R")
functions = Filter(is_function, file_parsed)
function_names = unlist(Map(function_name, functions))

Upvotes: 3

Views: 2039

Answers (1)

panman
panman

Reputation: 1341

Probably too late to join the party, but better late than never.

There is a package called NCmisc which has a function to list all functions in a file and returns a list where the names of the components are the names of the packages they belong to. If there are any functions in the global environment, they will be under the .GobalEnv list component. Simply load all packages the file uses and then run the following:

all.functions <- list.functions.in.file(
                       filename = "/path/to/file/my_file.R")

Upvotes: 3

Related Questions