简体   繁体   中英

perl @array data into R

a very simple doubt, but I do not know how to manage this.

I want to plot a histogram for all data in 'datos.txt'.

a) by using R:

datos<-scan("datos.txt")
pdf("xh.pdf")
hist(datos)
dev.off()

b) How could I invoke R inside Perl to do the same??

#!/usr/bin/perl
open(DAT,"datos.txt");
while (<DAT>) {
 chomp;
 push(@datos,$_);
}
#now I want a histogram of values in @datos

Thanks!!

Perl is not a statistics-focused language like R, so charting functions are not likely to be found in the core. But with Perl being a general purpose language, it can do anything R can, and you'll often find what you want by searching CPAN . A quick glance yields some promising candidates:

You can also try the perl module

Statistics::R .

This seems to be supported for windows and linux. I haven't really used it though. Thus, I don't know if it is easy to install (or if the installer pulls in a whole lot of dependencies, or how much manual configuration is required).

It seems to be pipe-based, and the OS-check for win32-based systems is really simple, so I'd think it works better on linux than on windows.

But the module seems to be actively developed (as of 2012). And for your use case, sending a few simple commands from perl to R, it should be worth a look.

At one point I decided I wanted a really simple command line barplot (easily adaptable to histogram or scatter plot etc) maker that I could stick at the end of a pipeline. I didn't know a lot of R at the time, nor did I know about littler (it might not have even existed yet) so I would up doing a hacky embedding of R in perl. It works, though. I wouldn't write it like this again since I know a heck of a lot more R now, but it has been useful to me as is. The only major problem is that since there is no event loop, the program has to be keep alive artificially to keep the window from disappearing. You will need the RSPerl package and scripts as explained here http://www.omegahat.org/RSPerl/


#!/usr/bin/perl -w
use strict;
use R;
use RReferences;

&R::startR("--no-save", "--silent");

my $header = <>;
chomp $header;
my @header = split(/,/, $header);
my @x;
my @y;

while(<>){
    chomp;
    my @fields = split(/,/);
    push(@x, $fields[0]);
    push(@y, $fields[1]+0);
}

R::callWithNames("barplot", {"height",\@y, "data",\@x, "xlab",$header[0], "ylab",$header[1] });

print "Ctrl-C to exit\n";
while(sleep(60)){}

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