Use rpy2 to run R script and convert to a pandas data frame

Summary

I would like to run R to create a dataframe that I want to convert to a pandas dataframe with rpy2. However, during that I face a NonImplementedError.

Steps to reproduce

Code snippet:

# test.py

import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
import streamlit as st

st.write("hello world")



pandas2ri.activate()
r = robjects.r
r.source('test_script.R') # <=== this is where it the exception is raised
with robjects.default_converter + pandas2ri.converter:
    dm_listing = robjects.conversion.get_conversion().rpy2py(robjects.r['r_df'])
# test_script.R

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
r_df <- data.frame(a = vec1, b = vec2)

However, the line r.source() raises the following error:

NotImplementedError: Conversion rules for `rpy2.robjects` appear to be missing. Those rules are in a Python contextvars.ContextVar. This could be caused by multithreading code not passing context to the thread.

If I run this without streamlit, it runs without any problems. Any ideas why this is failing or how I can fix this? I also considered using a subprocess command instead, but I am not sure how to convert this then into a pandas dataframe without saving an R dataframe and loading the file into a pandas dataframe instead.

Debug info

  • Streamlit version: 1.17.0
  • Python version: 3.10.8
  • virtualvenv version: 20.17.1
  • OS version: Manjaro Linux with Kernel 6.0.15-1
  • Browser version: Firefox 108.0.1

If any further information is required, please let me know. Thank you for your help.