Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array from php via command line to R

I have a problem, e am executing a R script from php via command line, and i need to give it two arrays for calculation.

I call the script by running:

Rscript nls.R ??? ???

??? and ??? are my arrays that i need to "give" to R, in order for it to calculate certain values.

Anyone knows how to do this? It is not limited to php, because it is command line - i just need to know if an array can be passed to R via command line and how.

How would R catch it, with what command?

Thanks a lot.

Regards

like image 216
Nemanja Avatar asked Aug 04 '11 14:08

Nemanja


2 Answers

The command you are looking for is commandArgs() .

Now, if you have for example a list if integers separated by commas in a string, you can get the integers

s = '1,2,3,4,5'
your_list = lapply(strsplit(s, ','), as.numeric)[[1]]

There might be more straight-forward ways achieving this.

EDIT:

better example (should also work with Rscript)

$ R "1,2,3,4,5"
...

>lapply(strsplit(commandArgs()[[2]], ','), as.numeric)[[1]]
[1] 1 2 3 4 5
like image 113
Timo Avatar answered Nov 11 '22 05:11

Timo


Assuming you want to run R in a process of serving a web page, there are some better ways of invoking R than command line; the problem is that R interpreter starts very slow and you are wasting lots of time and CPU power to start it over and over again.

You may for instance make a small R server with triggr and talk to it using a client made with PHP sockets.
The simpler yet heavier idea is to make an rApache app and either talk to it with CURL or use it directly as AJAX or even HTML provider.

like image 41
mbq Avatar answered Nov 11 '22 04:11

mbq