我通过 rmagic 使用 rpy2 在 jupyter 笔记本中将 R 代码与 python3 代码交错。一个简单的代码单元如下:
%%R -i df -o df_out
df_out <- df
返回一些已更改的列名称,例如CTB-102L5.4
变为 CTB.102L5.4
。我认为这与 read.table
或类似内容有关(根据 this answer )。但是我没有找到在 rmagic 扩展中指定这一点的方法。
我能想到的唯一解决方法是在将列名称传递给 R 之前更改列名称,并在数据帧返回 python 时恢复它们,但我想找到更好的解决方案。
最佳答案
每当使用参数-i <name>
时要将 Python 对象“导入”到 R 中,需要应用转换规则(请参阅 here )。默认转换器最终调用 R 的函数 data.frame
,这会将列名称(默认情况下参数 check.names=TRUE
,请参阅 https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/data.frame )清理为有效但未加引号的符号名称。在您的示例中,CTB-102L5.4
否则将被解析为表达式 CTB - 102L5.4
.
这种默认行为并不一定在每种情况下都需要,并且可以将自定义转换器传递给 R magic %%R
。
该文档包含有关编写自定义转换规则的简短介绍 ( https://rpy2.github.io/doc/v2.9.x/html/robjects_convert.html )。
假设您的输入是pandas
DataFrame,您可以按如下方式进行:
1- 实现 py2ri_pandasdataframe 的变体这不会净化名字。理想情况下只需设置 check.names
至FALSE
,尽管目前不可能,因为 https://bitbucket.org/rpy2/rpy2/issues/455/add-parameter-to-dataframe-to-allow )。
def my_py2ri_pandasdataframe(obj):
res = robjects.pandas2ro.py2ri_pandasdataframe(obj)
# Set the column names in `res` to the original column names in `obj`
# (left as an exercise for the reader)
return res
2- 创建从 ipython 转换器派生的自定义转换器
import pandas
from rpy2.ipython import rmagic
from rpy2.robjects.conversion import Converter, localconverter
my_dataf_converter = Converter('my converter')
my_dataf_converter.py2ri.register(pandas.DataFrame,
my_py2ri_pandasdataframe)
my_converter = rmagic.converter + my_dataf_converter
3- 使用%%R
与 --converter=my_converter
.
关于python - rpy2 rmagic 用于 ipython 将数据帧列名称中的破折号转换为点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49282218/