将R向量传递给PHP数组

将R向量传递给PHP数组

问题描述:

I am trying to pass the numeric vector from R to an array in PHP.

index.php:

<?php
    $n = 3;
    $out = array();

    exec("Rscript script.R $n", $out);

    $length = count($out);
    echo "length = ".$length."<br>";

    for($i = 0; $i < $length; $i++)
        echo "out[$i] = ".$out[$i]
?>

script.R:

#!/usr/bin/env Rscript

i <- as.numeric(commandArgs(TRUE))
print(i:10)

Output:

length = 1  
out[0] = [1] 3 4 5 6 7 8 9 10

As you can see from the above output, PHP is storing a R vector as a single element of an array. How do I store the individual elements of a R vector in PHP array?

I found the solution at php-r.

I changed my index.php as:

exec("Rscript my_script.R $n", $out);

$length = count($out);
for ($i = 0; $i < $length; $i++)
foreach (explode("
", $out[$i]) as $row) {
    If (strpos($row, ']') !== false)
        $numbersAsStr = substr($row, strpos($row, ']') + 1); 
    else
        $numbersAsStr = $row;
    foreach (explode(' ', $numbersAsStr) as $potentialNumber)
        if ($potentialNumber !== '')
            array_push($result, 0 + $potentialNumber);
}
var_dump($result);

Output:

array(8) { [0]=> int(3) [1]=> int(4) [2]=> int(5) [3]=> int(6) [4]=> int(7) [5]=> int(8) [6]=> int(9) [7]=> int(10) }