__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

import stata_setup

python

import stata_setup

stata_setup.config(‘c:/program files/stata17/’,’mp’)

**In Stata **

help python

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

https://www.stata.com/python/pystata/notebook/Quick%20Start0.html

A standard test to see if Python is running is to give the
command print('hello')

DOCUMENTATION

In
addition to
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/

https://blog.stata.com/2020/08/25/stata-python-integration-part-2-three-ways-to-use-python-in-stata/

The next blog should be unnecessary if you have already
installed these packages through e.g. installing Anacanonda

https://blog.stata.com/2020/09/01/stata-python-integration-part-3-how-to-install-python-packages/

Then there are several examples. The
following may be useful

https://blog.stata.com/2020/10/13/stata-python-integration-part-7-machine-learning-with-support-vector-machines/

https://blog.stata.com/2020/11/05/stata-python-integration-part-8-using-the-stata-function-interface-to-copy-data-from-stata-to-python/

** **

**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
command Rcall

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