使用rpy2的字符串格式转义

2024-10-04 05:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用rpy2在Python(2.7)中编写一个R函数,在R factorwars中有一个函数,它保存了包含字符串“reg”的方法中每个元素的索引:

from rpy2.robjects import r, pandas2ri
import rpy2.robjects as rob 
import pandas as pd
pandas2ri.activate()

rstring="""
function(methods){
factorvars=which(methods %in% 'reg')
}
"""
rfunc=rob.r(rstring)
new_data=rfunc(methods)

rstring实际上要长一点,我尝试在字符串后面使用“%sin%”%%和\%in%,但Python一直将其解释为%I并要求一个整数。你知道如何在Python中转义%in%或者在R中用%in编写类似的函数吗

编辑:包括更多的代码,导入和函数。问题是当我修改代码时,R代码会出错。任何python函数对于这个\都是\唯一的\字符串('某个字符串'),它可能会覆盖格式

%%in%%给出错误消息:

  <text>:9:41: unexpected 'in'
8:         fact = c('polyreg', 'logreg')
9:         factorvars=which(method_array %%in

Tags: 函数字符串代码inimportwhichasreg
2条回答

如果%被解释为printf样式的指令,请尝试将%符号加倍:%%in%%

一切似乎都在为此而努力:

>>> from rpy2 import robjects
>>> rstring = """ function(x) { x %in% c("a", "b") } """
>>> robjects.r(rstring)("a")
Out[6]: 
R object with classes: ('logical',) mapped to:
<BoolVector - Python:0x7f962c089608 / R:0x2919c88>
[       1]

相关问题 更多 >