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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀