一个更好的方式,从的R脚本中提取的功能呢? [英] A better way to extract functions from an R script?

查看:123
本文介绍了一个更好的方式,从的R脚本中提取的功能呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个文件myfuncs.R有几个功能:

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

我要放置载myfuncs.R内为自己的文件,适当命名的所有功能。我有一个简单的Bash-shell脚本来提取功能,并将它们放置在单独的文件:

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

让我:

func_A.R
func_B.R
func_C.R

不过,这个脚本有明显的局限性。例如,当函数'A'有一个嵌套函数就会胡作非为:

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?

推荐答案

来源的功能,然后键入 package.skeleton()

Source your functions and then type package.skeleton()

单独的文件将每个功能进行。

Separate files will be made for each function.

这篇关于一个更好的方式,从的R脚本中提取的功能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆