r - 使用 rPithon 包从 R 运行 Python 代码时出错

标签 r rpython

我想从 R 运行此 Python 代码:

>>> import nlmpy 
>>> nlm = nlmpy.mpd(nRow=50, nCol=50, h=0.75) 
>>> nlmpy.exportASCIIGrid("raster.asc", nlm)

Nlmpy 是一个用于构建中性景观模型的 Python 包。该示例来自website

要从 R 运行此 Python 代码,我尝试使用包 rPithon 。但是,我收到此错误消息:

if (pithon.available()) 
{ 
  nRow <- 50 
  nCol <- 50 
  h <- 0.75 

  # this file contains the definition of function concat 
  pithon.load("C:/Users/Anaconda2/Lib/site-packages/nlmpy/nlmpy.py") 
  pithon.call( "mpd", nRow, nCol, h) 

} else { 
  print("Unable to execute python") 
} 

Error in pithon.get("_r_call_return", instance.name = instname) : 
Couldn't retrieve variable: Traceback (most recent call last): 
File "C:/Users/Documents/R/win-library/3.3/rPithon/pythonwrapperscript.py", line 110, in <module> 
reallyReallyLongAndUnnecessaryPrefix.data = json.dumps([eval(reallyReallyLongAndUnnecessaryPrefix.argData)]) 
File "C:\Users\ANACON~1\lib\json\__init__.py", line 244, in dumps 
return _default_encoder.encode(obj) 
File "C:\Users\ANACON~1\lib\json\encoder.py", line 207, in encode 
chunks = self.iterencode(o, _one_shot=True) 
File "C:\Users\ANACON~1\lib\json\encoder.py", line 270, in iterencode 
return _iterencode(o, 0) 
File "C:\Users\ANACON~1\lib\json\encoder.py", line 184, in default 
raise TypeError(repr(o) + " is not JSON serializable") 
TypeError: array([[ 0.36534654,  0.31962481,  0.44229946, ...,  0.11513079, 
0.07156331,  0.00286971], [ 0.41534291,  0.41333479,  0.48118995, ...,  0.19203674, 
0.04192771,  0.03679473], [ 0.5188

此错误是由我的代码中的语法问题引起的吗?我使用适用于 Windows 的 Anaconda 4.2.0 平台,该平台使用 Python 2.7 版本。

最佳答案

我没有使用nlmpy包,因此,我不确定您的预期输出是什么。然而,这段代码成功地在 R 和 Python 之间进行通信。

有两个文件,

nlmpyInR.R

command ="python"
path2script="path_to_your_pythoncode/nlmpyInPython.py"

nRow <-50 
nCol <-50 
h <- 0.75

# Build up args in a vector
args = c(nRow, nCol, h)

# Add path to script as first arg
allArgs = c(path2script, args)

Routput = system2(command, args=allArgs, stdout=TRUE)
#The command would be python nlmpyInPython.py 50 50 0.75

print(paste("The Output is:\n", Routput))

nlmpyInPython.py

import sys
import nlmpy 
#Getting the arguments from the command line call
nRow = sys.argv[1]
nCol = sys.argv[2]
h = sys.argv[3]

nlm = nlmpy.mpd(nRow, nCol, h) 
pyhtonOutput = nlmpy.exportASCIIGrid("raster.asc", nlm)
#Whatever you print will get stored in the R's output variable. 
print pyhtonOutput

关于r - 使用 rPithon 包从 R 运行 Python 代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40667328/

相关文章:

r - 在 R 中,duplicated() 中的 fromLast 参数是否适用于整数64向量?

r - 为函数中的每一列添加 xlab 名称

python - RPython 将带引号的字符串从 R 复制到 Python

python - 无法使用 rPython 导入包

pypy - PyPy 中的 GIL 在哪里?

mysql - R统计 : Setting date as variable in MySQL Query

r - 将select_if与变量名称和类型条件一起使用

r - ggplot2:更改 `color`的顺序

signals - 在 RPython 中捕获信号

r - 使用 R 连接到 DynamoDB