rpy2 rmagic 用于 ipython 将数据框列名称中的破折号转换为点

rpy2 rmagic for ipython converting dashes to dots in dataframe column names

我正在通过 rmagic 使用 rpy2 将 R 代码与 jupyter 笔记本中的 python3 代码交错。一个简单的代码单元格:

%%R -i df -o df_out
df_out <- df

returns 一些列名称已更改,例如CTB-102L5.4 变为 CTB.102L5.4。我认为这与 read.table 或类似的(根据 this answer)有关。但是我没有找到在 rmagic 扩展中指定它的方法。

我能想到的唯一解决方法是在将列名传递给 R 之前更改列名,并在数据框返回 python 时恢复它们,但我想找到更好的解决方案。

每当使用参数 -i <name> 将 "import" 对象 Python 转换为 R 时,转换规则(参见 here). The default converter is ending up calling R's function data.frame, which will sanitize the column names (parameter check.names=TRUE by default, see https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/data.frame)将应用于 valid-yet-unquoted 符号名称.在您的示例中, CTB-102L5.4 否则将被解析为表达式 CTB - 102L5.4.

这种默认行为不一定适用于所有情况,可以将自定义转换器传递给 R 魔法 %%R

该文档包含有关编写自定义转换规则的简短介绍 (https://rpy2.github.io/doc/v2.9.x/html/robjects_convert.html)。

假设你的输入是一个pandas DataFrame,你可以进行如下操作:

1- 实施 py2ri_pandasdataframe that does not sanitize names. Ideally by just setting check.names to FALSE, although currently not possible because of 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