简体   繁体   中英

pass data from Perl to R

I want to pass the following data from perl to R and rescaled them (scale to [0, 1] ) in R by rescaler function and then send them back to Perl.

$m1 = 4;
$m2 = 5.3;
$m3 = 2; 
$m4 = 1; 
$m5 = 1.3; 
$m6 = 2;

I did:

my $R = Statistics::R->new() ;
$R->startR ;

$R->set('data', $m1 . ',' . $m2 . ',' . $m3 . ',' . $m4 . ',' . $m5 . ',' . $m6);
$R -> run(q`
library(reshape);
scaled_data <- rescaler(data, type="range");
`);
my $scaled_data = $R -> get('scaled_data');
print $scaled_data,"\n",$data,"\n";
$R->stopR();

but I get the following error.

Problem while running this R command:

library(reshape);
scaled_data <- rescaler(data);



Error:
x - mean(x, na.rm = TRUE) :
  non-numeric argument to binary operator
Calls: rescaler -> rescaler.default
In addition: Warning message:
In mean.default(x, na.rm = TRUE) :
  argument is not numeric or logical: returning NA
Execution halted

1) how can I pass the data correctly? 2) I think by this approach, the code will work slowly, do I need to send the data to R for rescaling?

@Len Jaffe and @MrFlick

I tried :

my $R = Statistics::R->new() ;
$R->startR;

$R->set('data', [ $m1 , $m2 , $m3 , $m4 , $m5 , $m6 ] );
$R -> run(q`library(reshape);scaled_data <- rescaler(data)`);
my $scaled_data = $R -> get('scaled_data');
print $scaled_data,"\n";
$R->stopR();

I got :

ARRAY(0xdde3d0)

Are you sure that you don't want:

  $R->set('data', [ $m1 , $m2 , $m3 , $m4 , $m5 , $m6 ] );

That's how the set commands are documented in the Perldoc for Statistics::R

Something like this within Perl should work

use List::Util qw( min max );

my @m = (4,5.3,2,1,1.3,2);
my $min = min @m;
my $max = max @m;
my @scaled = map {($_-$min)/($max-$min)} @m;

print join(" - ", @m), "\n";
print join(" - ", @scaled), "\n";

and that outputs

4 - 5.3 - 2 - 1 - 1.3 - 2
0.69767441860 - 1 - 0.23255813953 - 0 - 0.069767441860 - 0.23255813953

And I believe the main problem with your use of the Statistics::R package is the set command. R needed a vector so the set probably should have looked something like

$R->set('data', @m);
# or maybe $R->set('data', [$m1,$m2,$m3,$m4,$m5,$m6]);

but I do not have that package installed so i didn't test it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM