I'm looking for a way to call python within R on a Windows operating system. Since there appears to be no readily available R package for this (at least no package that's been updated recently), I'm looking for leads on how to write a set of commands in an R script that can then be sent in batch mode to python.
In short, how can I call python from R in a Windows OS?
Edit: To clarify, I am not asking about calling R from python; rather I am asking about calling python from R.
Update: Based on what I've gathered so far, here's a basic set of commands on running python from R in a Windows OS:
# (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 "my.py"), then you can run it in R as follows: system("python C:\\Users\\Name\\Desktop\\my.py") # or alternatively: system('python -c "import sys; sys.path.append(\'C:\\Users\\Name\\Desktop\'); import my;"')
Neither of these approaches is at the level of interactivity needed for fluid data analysis using python in R on a Windows OS. The most straightforward solution might be to write a simple R function that (1) exports a specified R data frame to python, (2) parses python syntax written in R (using stringr
and system('python -c')
), and then (3) optionally exports the data back to R. It'd be a pseudo-interactivity in R based on updating a temporary python file through the R console.
Type Conversions. If a Python object of a custom class is returned then an R reference to that object is returned. You can call methods and access properties of the object just as if it was an instance of an R reference class.
You can use Python with RStudio professional products to develop and publish interactive applications with Shiny, Dash, Streamlit, or Bokeh; reports with R Markdown or Jupyter Notebooks; and REST APIs with Plumber or Flask.
You can use this package PythonInR
Make a python file....
# -*- coding: utf-8 -*- """ Created on Wed Mar 9 09:55:46 2016 @author: Subhash Jaini """ import pandas as pd d = {'First' : [1., 2., 3.],'Second' : [1,2,3]} AA = pd.DataFrame(d) print(AA)
save it to a place (I used c:/deleteme/pythonRun.py)
In R, run this code.
#calls the python script to run in shell BlobReturnedFromPython = shell('python c:/deleteme/pythonRun.py',intern=TRUE) #get the first line and turn it to your header HEADER = gsub(" ","",unlist(strsplit(as.character(BlobReturnedFromPython[1])," ")))[-1] #all the rest of the data is non header data NONHEADER = BlobReturnedFromPython[2:(length(BlobReturnedFromPython)-1)] #turnthat blob (which is seperated by about 4 spaces ) DATA = data.frame(sapply(NONHEADER,function(x){unlist(strsplit(x," "))})) #brings those names into the data set names(DATA) <- HEADER DATA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With