take an r script output in python

To use R script output in Python, you can use the rpy2 module which allows for integration between Python and R. You can install rpy2 by running the command !pip install rpy2 in your Python environment.

Once you have rpy2 installed, you can import the rpy2.robjects module and use the r function to execute R code and get its output. Here's an example:

main.py
import rpy2.robjects as robjects

# define R code
r_script = """
my_vector <- c(1, 2, 3, 4, 5)
mean <- mean(my_vector)
sd <- sd(my_vector)
result <- list(mean=mean, sd=sd)
"""

# execute R code
robjects.r(r_script)

# access R output
r_output = robjects.r['result']
mean = r_output.rx2('mean')[0]
sd = r_output.rx2('sd')[0]

print(f"Mean: {mean}")
print(f"Standard deviation: {sd}")
383 chars
21 lines

In the above example, we define an R script that calculates the mean and standard deviation of a vector and saves the result in a list. We then execute the script using the r function and access the output using the rx2 method of the list object returned by r.

gistlibby LogSnag