Sunday, April 20, 2014

Python in R: Examples

How to call Python within R in Windows? This is a project I'd like to dedicate myself once I have more time, since every native R user would love to have at least pseudo-connectivity with Python.

Here's a short overview of how to run some Python code in R:

# (1) basic python commands called from R
system('python -c "a = 2 + 2; print a"') 
system('python -c "a = \'hello world\' ; print a; import pandas"')

# (2) if you have a python file you've already created (which I've 
# referred to as ""), then you can run it in R as follows:
system("python C:\\Users\\Name\\Desktop\\")

# or alternatively:
system('python -c "import sys; sys.path.append(\'C:\\Users\\Name\\Desktop\');
import my;"')