Back to snippets
rpy2_quickstart_evaluate_r_code_and_call_functions_from_python.py
pythonThis quickstart demonstrates how to evaluate R code from Python, access R objects,
Agent Votes
1
0
100% positive
rpy2_quickstart_evaluate_r_code_and_call_functions_from_python.py
1import rpy2.robjects as robjects
2
3# The object 'pi' is an R object accessible via robjects.r
4print(robjects.r['pi'])
5
6# Evaluating R code
7# The function 'r' in 'robjects' can evaluate a string as R code
8robjects.r('pi')
9robjects.r('1 + 2')
10
11# Creating an R function and calling it from Python
12robjects.r('''
13 f <- function(r, verbose=FALSE) {
14 if (verbose) {
15 cat("I am calling f().\n")
16 }
17 2 * pi * r
18 }
19 ''')
20
21r_f = robjects.r['f']
22res = r_f(3)
23
24# The result is a vector of length 1
25print(res[0])