【问题标题】:Strange behaviour with string passing to rpy2 - deleting leading zeros from string字符串传递给 rpy2 的奇怪行为 - 从字符串中删除前导零
【发布时间】:2021-10-13 06:24:37
【问题描述】:

我正在尝试在 rpy2 脚本中调用 python 字符串变量。该变量应该具有“01”的形状。

我遇到了以下行为:

import rpy2.robjects as robjects
string_to_pass = "01"
robjects.r('''print(paste("Output from R with format and paste:",{}))'''.format(string_to_pass))

将给出以下输出:

[1] "Output from R with format and paste: 1"

注意,字符串的前导零被切断了。

另一方面,这些行将按预期工作:

print("Output from python with format: {}".format(string_to_pass))
robjects.r('''print("Output from R with format: {}")'''.format(string_to_pass))
robjects.r('''print(paste("Output from R with pasting a string:", "01"))''')

输出:

Output from python with format: 01
[1] "Output from R with format: 01"
[1] "Output from R with pasting a string: 01"

有人可以解释一下这里发生了什么,只有在结合 python .format() 和 r paste() 时,以及如何避免它?

【问题讨论】:

    标签: python r python-3.x string rpy2


    【解决方案1】:

    我已经解决了这个问题

    string_to_pass = "'01'"
    robjects.r('''print(paste("Output from R with format and paste:",{}))'''.format(string_to_pass))
    

    注意额外的内引号,这对于 R 将其识别为字符串也很重要。

    【讨论】:

      【解决方案2】:

      查看作为 R 代码传递给 rpy2 以进行评估的字符串应该可以清楚地了解正在发生的事情。

      在第一种情况下,R代码字符串是:

      print(paste("Output from R with format and paste:", 01))
      

      数字 01 是 1,R 会打印它有一个这样的。要具有前导零,应使用 R 数字格式化函数。

      第二种情况是:

      print(paste("Output from R with format and paste: 01"))
      

      【讨论】:

        猜你喜欢
        • 2011-04-09
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 2018-07-27
        • 2019-10-20
        • 2015-12-25
        相关资源
        最近更新 更多