使用 rpy2 为 R 准备一个 python 字符串 [英] Prepare a python string for R using rpy2

查看:39
本文介绍了使用 rpy2 为 R 准备一个 python 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与 python 变量到 R 和也许也是这个 python 对象到 rpy2 但两者都不完全重叠,第一个一个实际上是没有答案的.

This question relates to python variable to R and perhaps also to this python objects to rpy2 but none of the two completely overlaps and the first one is actually unanswered.

我的问题其实很简单.我有一个字符串,比如:

My question is actually very simple. I have a string, say:

In [21]: strg
Out[21]: 'I want to go home'

我想通过 robjects.r(''' ''') 像这样将它传递给 R,例如:

and I want to pass it to R through robjects.r(''' ''') like this, for example:

robjects.r('''

test <- gsub("to", "",strg)

''')

当然,当我运行它时,我得到:Error in gsub("me", "", strg) : object 'strg' not found.

but of course, when I run this I obtain: Error in gsub("me", "", strg) : object 'strg' not found.

我没有太多使用 rpy2(很明显),但我猜这与 R 和 Python 看到对象的环境有关.

I have not used rpy2 much (as obvious) but I guess is related to the environments in which R and Python see the objects.

我尝试了一些方法,例如先将字符串 strg 转换为 robject,然后将其提供给 robjects.r(''' ''') 但我收到相同的错误消息.总的来说,我不知道如何做到这一点,以便在 R 环境中看到 strg.

I have tried a few things, like transforming the string strg to an robject first and then feed it to robjects.r(''' ''') but I get the same error message. Overall, I do not know how do this so that strg is seen at the R environment.

非常感谢任何帮助!

提前感谢您的时间!

推荐答案

只需将 strg 值添加到命令字符串中即可:

Just add the strg value to the command string:

robjects.r('''

test <- gsub("to", "",''' + strg + ''')

''')

或者,通过使用 .format:

robjects.r('''

test <- gsub("to", "",%s)

'''.format(strg))

请注意,您需要注意反斜杠,请参阅问题 这里

Do note that you'll need to watch out for backslashes, see the question here

这篇关于使用 rpy2 为 R 准备一个 python 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆