|
| 1 | +Integrate R code (:mod:`.util.r`) |
| 2 | +********************************* |
| 3 | + |
| 4 | +Developers working with :mod:`message_ix_models` can integrate existing R codes or use R to perform data processing related to building, running, and reporting models. |
| 5 | +:mod:`message_ix_models.util.r` provides utility code to help with using :mod:`rpy2` to achieve this integration. |
| 6 | + |
| 7 | +Two patterns are supported. |
| 8 | +To use either, place a :file:`r_code.R` *in-line* in the source tree, either in :mod:`message_ix_models`, :mod:`message_data`, or another package:: |
| 9 | + |
| 10 | + message_ix_models/ |
| 11 | + project/ |
| 12 | + example/ |
| 13 | + __init__.py |
| 14 | + module_a.py |
| 15 | + module_b.py |
| 16 | + r_code.R |
| 17 | + |
| 18 | +The patterns are: |
| 19 | + |
| 20 | +.. contents:: |
| 21 | + :local: |
| 22 | + :backlinks: none |
| 23 | + |
| 24 | + |
| 25 | +R ‘Modules’ |
| 26 | +=========== |
| 27 | + |
| 28 | +In this pattern, :func:`get_r_func` is used to source (i.e. import or run) R code from a file that defines one or more functions or other objects. |
| 29 | +:func:`get_r_func` returns this function, which can then be called from Python code. |
| 30 | +In this way, the R source file functions somewhat like a Python **‘module’**, while still being lighter weight than a full, installable R package. |
| 31 | + |
| 32 | +.. code-block:: R |
| 33 | + :caption: :file:`r_code.R` |
| 34 | +
|
| 35 | + # R file that defines functions and other entry points |
| 36 | +
|
| 37 | + mul <- function(x, y) { |
| 38 | + # Multiply operands |
| 39 | + return(x, y) |
| 40 | + } |
| 41 | +
|
| 42 | +.. code-block:: python |
| 43 | +
|
| 44 | + from message_ix_models.util import get_r_func |
| 45 | +
|
| 46 | + # Source r_code.R, retrieve the function named "mul" |
| 47 | + mul = get_r_func("message_ix_models.project.example.r_code:mul") |
| 48 | +
|
| 49 | + # Call the function |
| 50 | + result = mul(1.2, 3.4) |
| 51 | +
|
| 52 | + # …use `result` in further Python code |
| 53 | +
|
| 54 | +.. currentmodule:: message_ix_models.util.r |
| 55 | + |
| 56 | +.. autofunction:: get_r_func |
| 57 | + |
| 58 | + |
| 59 | +Stand-alone scripts |
| 60 | +=================== |
| 61 | + |
| 62 | +In this method, the R script is placed inline. |
0 commit comments