Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to extract functions from an R script?

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?

like image 280
Andy Barbour Avatar asked Nov 07 '25 19:11

Andy Barbour


1 Answers

Source your functions and then type package.skeleton()

Separate files will be made for each function.

like image 92
GSee Avatar answered Nov 10 '25 17:11

GSee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!