I am trying to call a python string variable within a rpy2 script. The variable is supposed to have the shape "01".
I encountered the following behaviour:
import rpy2.robjects as robjects
string_to_pass = "01"
robjects.r('''print(paste("Output from R with format and paste:",{}))'''.format(string_to_pass))
will give the following output:
[1] "Output from R with format and paste: 1"
Note, that the leading zero of the string was cut off.
On the other side, these lines will work as expected:
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"))''')
with the output:
Output from python with format: 01
[1] "Output from R with format: 01"
[1] "Output from R with pasting a string: 01"
Can sombody please explain what is happening here, only when combining python .format() and r paste(), and how to avoid it?
I have solved the problem by saying
string_to_pass = "'01'"
robjects.r('''print(paste("Output from R with format and paste:",{}))'''.format(string_to_pass))
Note the additional inner quotation marks which seem to be important for R to recognize it as a string aswell.