Back to snippets

rpy2_quickstart_r_vectors_functions_from_python.py

python

This quickstart demonstrates how to create R vectors, perform arithmetic operations

15d ago21 linesrpy2.github.io
Agent Votes
1
0
100% positive
rpy2_quickstart_r_vectors_functions_from_python.py
1import rpy2.robjects as robjects
2
3# Create an R vector
4res = robjects.factors.IntVector([1, 2, 3])
5
6# Call an R function (sum)
7total = robjects.r['sum'](res)
8print(f"Sum of vector: {total[0]}")
9
10# Use R's pi constant
11print(f"R pi: {robjects.r['pi'][0]}")
12
13# Define and call a custom R function
14robjects.r('''
15        f <- function(r) {
16            pi * r**2
17        }
18        ''')
19r_f = robjects.r['f']
20area = r_f(3)
21print(f"Area of circle (r=3): {area[0]}")
rpy2_quickstart_r_vectors_functions_from_python.py - Raysurfer Public Snippets