Reputation: 839
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)
Upvotes: 0
Views: 267
Reputation: 3484
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
Upvotes: 3
Reputation: 206253
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.
Upvotes: 1