[R] send command to other program

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Apr 29 12:05:23 CEST 2009


Jim Lemon wrote:
> thoeb wrote:
>> Hello,
>> does anybody know about how to "send" a command or a text line from R to
>> another program? I have written a script in which several
>> calculations are
>> made and outputfiles (csv) are generated. Afterwards I open another
>> program
>> (Fortran) via shell.exec. This program asks for the names if the output
>> files and it would be quite practically if it could just adopt the file
>> names from the r script.
>>   
> Hi Tamara,
> If the succeeding program can read the name of the input file via the
> command line arguments, like:
>
> myfortranprogram -i myfile.csv
>
> you can include the arguments in the shell call. Alternatively, you
> could have R write a shell script that would execute the program with
> the appropriate arguments, then call the shell script from R. Of
> course if your program has to have keyboard input for the filename,
> you would have to resort to magic like writing the filename into the
> keystroke buffer.


if your r code produces just the file names, each on a separate line,
and the other program takes file names from the args list with no
particular option needed to specify them, you might try:

    r <your r script> | xargs <your program>
    <your program> $(r <your r script>)

as in

    # dummy files and scripts
    echo "foo" > foo
    echo "bar" > bar
    echo "cat(paste(c('foo', 'bar'), '\n', collapse=''))" > script.r
    echo 'for f in "$@"; do echo "input: $f"; done' > program
    chmod 755 program

    r script.r | xargs ./program
    ./program $(r script.r)
  
you may need to adapt the pattern to a shell other than bash.

vQ




More information about the R-help mailing list