Executing an R script in python via subprocess.Popen

前端 未结 5 543
逝去的感伤
逝去的感伤 2021-01-20 23:25

When I execute the script in R, it is:

$ R --vanilla --args test_matrix.csv < hierarchical_clustering.R > out.txt

In Python, it works if

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 00:21

    Keven's solution works for my requirement. Just to give another example about @Kevin's solution. You can pass more parameters to the rscript with python-style string:

    import subprocess
    
    process = subprocess.Popen(["R --vanilla --args %s %d %.2f < /path/to/your/rscript/transformMatrixToSparseMatrix.R" % ("sparse", 11, 0.98) ], shell=True)
    process.wait()
    

    Also, to make things easier you could create an R executable file. For this you just need to add this in the first line of the script:

    #! /usr/bin/Rscript --vanilla --default-packages=utils
    

    Reference: Using R as a scripting language with Rscript or this link

提交回复
热议问题