dongshun5963 2016-02-02 09:19
浏览 240
已采纳

R扩展:在包中调用外部脚本

I'm writing an R package which, among other things, defines a function which is actually a wrapper for a PHP script. Let's assume the PHP script offers some functionality that is considerably difficult to recreate in R and that my line of reasoning (wrapping a PHP script in R) makes sense.

I'm currently keeping the PHP script in a separate file, and running it via a system call.

My R function/wrapper looks like this:

wrapper <- function() {

  # I'm not entirely sure what the path to the PHP file should be
  php_file_name <- "magic_in.php"
  php_script_argument <- "hello, world"

  system_call <- sprintf('php -f "%s"', php_file_name, php_script_argument)
  system(system_call)

}

while the magic_in.php file is the following:

<?php

    print($argv[1]."
")

?>

But this solution sucks - the system call works only if I have the PHP script in my current working directory.

I keep the wrapper in a ~/simple_package/R/wrapper.R file, but I'm not sure where to store the PHP script.

Am I supposed to keep the PHP file in a ~/simple_package/src directory and then call it using some dedicated R function (like .Call for C executables)?

  • 写回答

2条回答 默认 最新

  • dongshilve4392 2016-02-02 14:48
    关注

    Probably /data is not the best option for package scripts, /exec could be a better choice.

    See:

    You may also consider using system2:

    For some languages (Python), there is some special support in CRAN


    An example (using system and system.file):

    It is executed by an external R script command-line:

    #!/bin/env Rscript
    
    args <- commandArgs(TRUE)
    if( length(args) < 2 ){
        stop( "usage : R CMD execute package script [parameters]
    " )
    }
    package <- args[1]
    script <- args[2]
    scriptfile <- file.path( system.file( "exec", script, package = package ) ) # <= path
    if( !file.exists( scriptfile ) ){
        stop( sprintf( "file not found: '%s' ", scriptfile  ) )
    }
    
    trail <- if( length(args) > 2 ) paste( tail( args, -2 ), sep = " " ) else ""
    cmd <- sprintf( '"%s" %s', scriptfile, trail )
    
    system( cmd ) # <= or system2 ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置