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?
Source your functions and then type package.skeleton()
Separate files will be made for each function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With