A. Colin Cameron: Using Python within Stata
It can be useful to run Python within Stata. For example, data can be set up in Stata and then transferred from Stata to Python.
LINK STATA TO PYTHON
Update Stata to latest version. Need Stata 17 or 16.
In Anaconda go to CMD launch
pip install stata_setup
If this does not work then in Stata give command
python set exec “c:/ProgramDatata/Anaconda3/python.exe”, permanently
or python set exec c:/ProgramDatata/Anaconda3/python.exe, permanently
A standard test to see if Python is running is to give the command print('hello')
help python and the associated pdf manual entry
go to https://www.stata.com/python/api17/ for Stata’s Python API documentation (sfi)
and see the blogs https://blog.stata.com/2020/08/18/stata-python-integration-part-1-setting-up-stata-to-use-python/
The next blog should be unnecessary if you have already installed these packages through e.g. installing Anacanonda
Then there are several examples. The
following may be useful
ASIDE: USING R WITH STATA
Stata has no built-in link with R.
To use Stata within R there is an R package Rstata
To use R from Stata there is a Stata user-written
Alternatively to use R within Stata one can use the Stata shell command.
This varies with computer operating system – in Stata type help shell
The following Stata example in Windows executes an R program (here myRprogram.R) that reads in a Stata dataset, does some calculations, and updates the dataset. The Stata dataset needs to be version 12 as R does not read later versions.
saveold "./results/appdat.dta", replace version(12)
shell /Library/Frameworks/R.framework/Resources/bin/R --vanilla < myRprogram.R
use "./results/appdat.dta", clear
A. Colin Cameron / UC-Davis Economics / http://www.econ.ucdavis.edu/faculty/cameron