[R] Calling R functions in Delphi

Tom Backer Johnsen backer at psych.uib.no
Tue Dec 5 18:36:08 CET 2006


Anna Belova wrote:
> Hello All,
> 
> We would like to call quantile() function from the R-package STATS in a
> Delphi program. If this is possible, could anyone provide us with an
> example?

It is possible, and in principle simple.  The essentials:  (1) Write a 
file containing the something like a script in R with whatever 
commands. (2) Start a process involving the execution of R with a 
command line containing two arguments, the name of the command file 
and the file where you want the output (results) to be. (3) wait for 
the process to stop.  So, here is a function (returns true if 
everyhing worked OK) that does that:

function StartRAndWait (CommandLine : string) : Boolean;
var
    Proc_info: TProcessInformation;
    Startinfo: TStartupInfo;
    ExitCode: longword;
    CreateOK : Boolean;
begin
    Result := False;

    { Initialize the structures }

    FillChar(proc_info, sizeof (TProcessInformation), #0);
    FillChar(startinfo, sizeof (TStartupInfo), #0);
    Startinfo.cb := sizeof (TStartupInfo);
    Startinfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
    Startinfo.wShowWindow := SW_HIDE;

    { Attempt to create the process. If successful wait for it to end}

    CreateOK := CreateProcess(Nil, PChar('R.exe ' + CommandLine), nil,
       nil,False, CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS, nil,
       nil, StartInfo, proc_info);
    if (CreateOK) then begin
       WaitForSingleObject (proc_info.hProcess, INFINITE);
       GetExitCodeProcess(proc_info.hProcess, ExitCode);
       Result := True
       end;
    CloseHandle(proc_info.hThread);
    CloseHandle(proc_info.hProcess);
    end;

The argument for the procedure (CommandLine) is a string, created by a 
statement like:

Command := 'CMD BATCH ' + CommandFileName + ' ' + TempFileName;

where CommandFileName is the name of the file with the script, and 
TempFileName is the name of the text file containing the output. The 
procedure is fairly lowlevel, but it worked for me using Delphi 7.  I 
do not remember how I managed to put this together (probably a mix of 
help from the R and Delphi lists), so please do not ask questions 
about the finer details.

Tom


+----------------------------------------------------------------+
| Tom Backer Johnsen, Psychometrics Unit,  Faculty of Psychology |
| University of Bergen, Christies gt. 12, N-5015 Bergen,  NORWAY |
| Tel : +47-5558-9185                        Fax : +47-5558-9879 |
| Email : backer at psych.uib.no    URL : http://www.galton.uib.no/ |
+----------------------------------------------------------------+




More information about the R-help mailing list