http://www.perlmonks.org?node_id=1009059


in reply to Re: Calling R in perl
in thread Calling R in perl

Ok, thank you very much to all for the replies. Statistics::R seens to be what I want.

I've installed Statistics::R

But I have some issues.

My code is this:

#!/usr/bin/perl use strict; use warnings; use Statistics::R; my @lines; my $line; my $csv_check = shift @ARGV; #Mark for csv check----- @ARGV = $csv_check; while ( defined( $line = <> ) ) { push @lines, $line; } save_array_output(@lines, ".out"); print "\@lines = \n @lines "; my $R = Statistics::R->new() ; $R->startR ; $R -> send('library(genetics);'); $R -> send('table <- read.table("/home/user/my_path/data_freq.txt.out" +, header=T, row.names=2);'); $R -> send('g1 <- table[, 2];'); $R -> send('meang1 <- mean(g1)'); $R -> send('print(meang1);'); $R -> send('write.table(g1, "/home/user/my_path/g1.txt");'); $R -> send('write.table(meang1, "/home/user/my_path/meang1.txt");'); #my @results1 = get('g1'); print "\@results1 = ", @results1, "\n"; $R->stopR() ; #----------------------------------------------- sub save_array_output { @lines = @_; my $mid_name = pop @lines; my $output_name = $csv_check.$mid_name; open(MYOUTFILE, ">:utf8", $output_name); # Open output file print MYOUTFILE "@lines \n"; close(MYOUTFILE); # Close output file }

data_freq.txt is this:

Locus Alleles frequencies Bet01 230 0.166666666666666657415 Bet01 238 0.500000000000000000000 Bet01 244 0.333333333333333314830 Bet05 101 0.285714285714285698425 Bet05 103 0.500000000000000000000 Bet05 105 0.142857142857142849213

I run my program with "./perl-R3.pl data_freq.txt". I am able to call R, activate the genetics package, make it run the file data_freq.txt.out, do the calculations, save the results in "g1.txt" and "meang1.txt".

OK.

But I cant get back g1 to perl.

If I uncomment the line "#my @results1 = get('g1');", I get this error:

Undefined subroutine &main::get called at ./perl-R3.pl line 35.

If I try to pass values from perl to R directly with a command like "$R -> set('table', \@lines);", I also receive an error:

Can't locate object method "set" via package "Statistics::R" at ./perl-R3.pl line ##

Whats the problem here?

Also, if I try to set the work directory to R with a command like "$R -> send('setwd("/home/user/my_path/");');", the program hangs.