3

How can I convert the jupyter R magics like %%R or %Rpush or %Rpull or the execution of an R function into a regular python script?

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292
  • 1
    Do you want an automatic conversion? One possibility is to put all the %%R cells into a script and then use `subprocess` to call the script. [This question](http://stackoverflow.com/questions/24544190/calling-r-script-from-python-using-rpy2) suggests using `rpy2` with `r.source("script.R")` – cd98 Oct 24 '16 at 22:13
  • Automatic conversion sounds great! – Georg Heiler Oct 25 '16 at 05:46
  • You mean like: http://stackoverflow.com/questions/6434569/executing-an-r-script-in-python-via-subprocess-popen `process = subprocess.Popen(['R', '--vanilla', '--args', '\\%s_DM_Instances_R.csv\\' % output_filename, '<', '/home/kevin/AV-labels/Results/R/hierarchical_clustering.R'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) process.communicate()#[0] is stdout` but how whould %Rpush / %Rpull work? – Georg Heiler Oct 25 '16 at 05:48
  • In Jupyter I already have a single %%R function which takes the arguments via %Rpush and I get the result via %Rpull I just would like to put it into a "normal" python script without the jupyter magics dependencies. – Georg Heiler Oct 25 '16 at 05:49
  • And here https://www.r-bloggers.com/integrating-python-and-r-part-ii-executing-r-from-python-and-vice-versa/ system2 is used for the subprocess. Is this "required"? – Georg Heiler Oct 25 '16 at 05:53
  • @cd98 I need to pass an array to my R function. following http://rpy2.readthedocs.io/en/version_2.8.x/introduction.html it is easy to get hold of the R function; however, just passing [0, 1, 0, 0, 0, 1, 1, 1, 1] fails with an error: 'x' must be atomic for 'sort.list'. How should I implement %Rpush / %Rpull functionality? as %%R e.g. just executing a R function already seems to work fine. – Georg Heiler Oct 27 '16 at 12:09

1 Answers1

0

The answer is partly in the comments above: http://rpy2.readthedocs.io/en/version_2.8.x/introduction.html#creating-rpy2-vectors here is a nice and longer explanation This is the solution to the last mentioned problem of implementing a %Rpush robjects.IntVector([1, 2, 3])

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292