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


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

OK, I think a couple changes will fix everything.

First, the method for running a line of R code is run(), not send(), so change $R->send(...) to $R->run(...). (The method send() still works, but seems to have been deprecated for a long time. I'd avoid its use in case it is ever completely dropped.)

Second, to retrieve values from R, you need to change my @results1 = get('g1'); to my $results = $R->get('g1'). Notice that there are two changes here: (1) the addition of $R-> and (2) $results is an array reference rather than an array.

Regarding your problem with $R->set(), can you show a few lines of code where you are using it in context? I don't see any obvious problems with what you wrote there.

One more thing: you are putting your R commands in single quotes, but the Statistics::R docs recommend quoting with q`...` (if you aren't interpolating Perl variables) or qq`...` (if you are interpolating). Those are backticks, by the way (but, really, any character not used in typical R code should suffice). The reason for this is that if you have single or double quotes in your R commands, you won't run into troubles. Another thing to watch out for is if you are wrapping your R code in double quotes because you need to interpolate Perl variables and are using $ in your R code to specify a column of data, for example, you need to escape it (e.g., dataframe\$sample1).

EDIT: I'm trying to understand why you are having issues with $R->set(). Are you able to run the following code successfully? Also, I don't think it is causing any errors, but you should remove the spaces between your objects and methods (e.g., change $R -> set(...) to $R->set(...))

#!/usr/bin/env perl use strict; use warnings; use Statistics::R; my @numbers = ( 1 .. 10 ); my $R = Statistics::R->new(); $R->set( 'x', \@numbers ); $R->run( q`x = x ^ 2` ); my $squares = $R->get('x'); print "@$squares"; __END__ 1 4 9 16 25 36 49 64 81 100