I want to write an R function in RMarkdown, where I declare an R object inside the function and then convert this object to a Python object that I then pass to a Python function. However, during the conversion part I get and error in py_run_string_impl(code, local, convert).
Below is a minimal working example that showcases, in principle, what I'm trying to achieve and highlights the issue that I'm having:
knitr::opts_chunk$set(echo = TRUE)
Import reticulate and define an R object:
library(reticulate)
a = 5 # Variable declared in global environment
Define an R function:
printPython = function(){
b = 2 # Variable declared within the scope of the function
# Attempt to translate both to python and run a python command:
py_run_string("print(r.a)")
py_run_string("print(r.b)")
}
Execute the function:
printPython()
This throws: Error in py_run_string_impl(code, local, convert) : RuntimeError: Evaluation error: object 'b' not found.
Re-declare 'b' in the global environment and run printPython() again:
b = 2
printPython()
The function now runs fine. If reticulate is imported inside the function the issue persists:
printPython2 = function() {
library(reticulate)
x=2
py_run_string("print(r.x)", local = TRUE)
}
printPython2()
Throws the same error as before.
If I assign the declared variable to the global environment (YUCK) the function once again run fine:
printPythonGlobal = function() {
assign("x", 2, envir = globalenv())
py_run_string("print(r.x)", local = TRUE)
}
printPythonGlobal()
What is the proper way to do conversions of R objects declared inside of a function? How can I do this without having to resort declaring variables inside the function as global (which is generally highly discouraged)?