Search code examples
pythonrrpy2

Just run a single R command from rpy2 (not a source file)


I am very new to rpy2 and I want to use it to just run a single R command. I know the source() function which takes a file path as the argument string, but I do not want to write a single line to a file and call source() to run that line as this looks kinda indirect way to run a single line. I am wondering whether there is another function (named run_command() in below example) which just runs the line given as the argument.

Example: run_command("a=3+5")


Solution

  • You can run r commands by using robjects.r from rpy2

    from rpy2 import robjects
    
    robjects.r('a=3+5')
    
    #To save the output
    r_result=robjects.r('a=3+5')
    print(r_result[0])
    
    8.0