PHP code example of kachkaev / php-r
1. Go to this page and download the library: Download kachkaev/php-r library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kachkaev / php-r example snippets
use Kachkaev\PHPR\RCore;
use Kachkaev\PHPR\Engine\CommandLineREngine;
$r = new RCore(new CommandLineREngine('/path/to/R'));
$result = $r->run(<<<EOF
x = 1
y = 2
x + y
x + z
x - y
EOF
);
echo $result;
echo $r->run("x = 100")
echo "\n=====\n"
echo $r->run("x * x")
use Kachkaev\PHPR\RCore;
use Kachkaev\PHPR\Engine\CommandLineREngine;
$r = new RCore(new CommandLineREngine('/path/to/R'));
$rProcess = $r->createInteractiveProcess();
$rProcess->start();
$rProcess->write('x = 100');
// Do something else
$rProcess->write('x * x');
echo $rProcess->getAllResult();
$rProcess->write(<<<EOF
x = 1
y = 10 + (x
+ x / 2)
z = 42
EOF
);
$rProcess->write('x = 1 + (');
// IncompleteRCommandException
$rProcess = $r->createInteractiveProcess();
$rProcess->start();
$rProcess->write(<<<EOF
x = 1
y = 2
x
y
EOF
);
$rProcess->write(<<<EOF
x + 41
x + xxx
x + y
EOF
);
echo $rProcess->getLastWriteInput();
// x + 41
// x + xxx
// x + y
echo $rProcess->getLastWriteOutput();
// 42
//
// [1] 3
echo $rProcess->hasLastWriteErrors();
// true
echo $rProcess->getLastWriteErrorCount();
// 1
$errors = $rProcess->getLastWriteErrors();
echo $errors[0]->getErrorMessage()
// object 'xxx' not found
echo $errors[0]->getCommand()
// x + xxx
$rProcess->getAllInput();
$rProcess->getAllOutput();
$rProcess->hasErrors();
$rProcess->getErrorCount();
$rProcess->getErrors();
$rProcess = $r->createInteractiveProcess();
$rProcess->start();
$rProcess->write(<<<EOF
x =
1 + 1
y
x
EOF
);
$inputAsArray = $rProcess->getAllInput(true);
// ['x ={newline}1 + 1', 'y', 'x']
$outputAsArray = $rProcess->getAllOutput(true);
// ['', null, '2']
$resultAsArray = $rProcess->getAllResult(true);
// [
// ['x ={newline}1 + 1', '', null],
// ['y', null, 'Error: object \'y\' not found'],
// ['x', '2', null]
// ]
$rProcess->setErrorSensitive(true);
$rProcess->write('x = 1 + missingVariable');
// RErrorsException
$rProcess->setErrorSensitive(false);
$rProcess->write('x = 1 + missingVariable');
if ($rProcess->hasLastWriteErrors()) {
throw new RErrorsException($rProcess->getLastWriteInput(true), $rProcess->getLastWriteOutput(true), $rProcess->getLastWriteErrors());
}
$allErrors = $rErrorsException->getErrors();
if (count ($allErrors) > 1) {
$secondError = $allErrors[1];
echo $secondError->getErrorMessage();
}
use Kachkaev\PHPR\ROutputParser;
$rOutputParser = new ROutputParser();
$rProcess->write('21 + 21');
var_dump($rProcess->getLastWriteOutput());
// string(6) "[1] 42"
var_dump($rOutputParser->singleNumber($rProcess->getLastWriteOutput()));
// int(42)