4

Say I have a file "myfuncs.R" with a few functions in it:

A <- function(x) x
B <- function(y) y
C <- function(z) z

I want to place all the functions contained within "myfuncs.R" into their own files, named appropriately. I have a simple Bash-shell script to extract functions and place them in separate files:

split -p "function\(" myfuncs.R tmpfunc
grep "function(" tmpfunc* | awk '{
  # strip first-instances of function assignment
  sub("<-", " ")
  sub("=", " ")
  sub(":", " ")  # and colon introduced by grep
  mv=$1
  mvto=sprintf("func_%s.R",$2)
  print "mv", mv, mvto
}' | sh

leaving me with:

func_A.R
func_B.R
func_C.R

But, this script has obvious limitations. For example, it will misbehave when function 'A' has a nested function:

A <- function(x){
    Aa <- function(x){x}
    return(Aa)
}

and outright fails if the whole function is on a single line.

Does anyone know of a more robust, and less error-prone method to do this?

Andy Barbour
  • 8,783
  • 1
  • 24
  • 35

1 Answers1

8

Source your functions and then type package.skeleton()

Separate files will be made for each function.

GSee
  • 48,880
  • 13
  • 125
  • 145
  • 3
    Note that `dump` is the function used in `package.skeleton()` to write the text representations of 'function' objects. So, if you just wanted to save the functions and not deal with the package framework, you could use that. – Andy Barbour Nov 06 '12 at 23:00