我正在尝试运行一个比较测试,该测试需要对来自python脚本和R脚本的结果进行多次迭代。使用网格化程序包中的repl_python(),每件事都可以在一次迭代中运行;但是,如果我试图在循环中运行它来获取复制,它就不能工作。
关于如何让python代码块在R中的循环中工作的想法?
###################################################
x <- 0
#run this line by line 5 times, end up with x = 5
repl_python()
a = r.x
a = a + 1
exit
x <- py$a
#####################################
#try to run this, and it just freezes
#i stays at 1 and x stays at 0
x <- 0
for (i in 1:5){
repl_python()
a = r.x
a = a + 1
exit
x <- py$a
}发布于 2019-06-08 23:50:17
我自己解决了这个问题;不出所料,阅读网格化软件包的小字是关键。问题是repl_python()只能在控制台中工作。要在脚本中运行python代码行,请使用py_run_string(),如下所示:
x <- 0
for (i in 1:5){
py_run_string("a = r.x")
py_run_string("a = a + 1")
x <- py$a
}
x希望这能帮助其他人不要像我一样浪费时间。
发布于 2019-11-05 00:17:16
我找到了解决这个问题的方法
编写python代码并保存为.py文件
之后,使用命令source_python('path_to_code.py')运行python代码
如下所示:
#### Python part #####
a = r.x
a = a + 1
#### R part #####
for (x in 1:10) {
source_python('python_part.py')
print(a)
}https://stackoverflow.com/questions/56480754
复制相似问题