rpy2 running R function
<p>I have an R function</p>

<pre><code> square_num &lt;- function(x) {
     return(x*x)
 }
</code></pre>

<p>when I run this via rpy2 as:</p>

<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num &lt;- function(x) {
     return(x*x)
}    
"""

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)
</code></pre>

<p>it works.</p>

<p>When I have the function inside an R file and run it using</p>

<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
with open('Algo.r', 'r') as f:
    string = f.read()

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)
</code></pre>

<p>I get:</p>

<pre><code>Traceback (most recent call last):
  File "Main.py", line 25, in &lt;module&gt;
    testy = STAP(string, "testy")
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line     290,  in __init__
reval(string, env)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line 75, in reval
p = rinterface.parse(string)
rpy2.rinterface.RParsingError
</code></pre>

<p>The function is the same in both instances. I just copied and pasted it into a .r file?</p>

<p>Did you check the content of your Python variable <code>string</code> ? </p>

<p>The following should work:</p>

<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num &lt;- function(x) {
     return(x*x)
}    
"""

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)

with open('algo.R', 'w') as fh_out:
    fh_out.write(string)

with open('algo.R', 'r') as f:
    string_again = f.read()

testy = STAP(string_again, "testy")

Jack = testy.square_num(10)
print(Jack)
</code></pre>

python rpy2