Launch and Interact with a STATA Session

Launch and Interact with a STATA Session

Yesterday, I found a interesting R Package on GitHub - bubble. This package provides a REPL (交互解释器) between R and node. And its source codes are quiet simple, so I want to know if I can create a Stata REPL by imitating it. Then we have statarepl package which provides a REPL interface between R and Stata, it’s different from RStata, which I have introduced before.

The goal of {statarepl} is to launch and interact with a Stata session from R.

Installation

You can install the dev version of {statarepl} with:

R
1
remotes::install_github("czxa/statarepl", dependencies = TRUE)

Example

Note that you’ll need to have stata-se or stata-mp installed on your machine.

Using statarepl to launch and communicate with a Stata session

Launch a new Stata session with StataSession$new().

This function uses the path to your Stata binary. On MacOS, it can be found with Sys.which("stata-se") or Sys.which("stata-mp")

StataSession$new() tries to guess where Stata is by looking at both these Sys. If they are both empty, you’ll get an error, and need to provide the path manually. The function to find Stata is exported and called find_stata(). It will either return the path to your local installation of Stata or an error.

1
2
3
4
library(statarepl)
find_stata()
#> stata-se
#> "/usr/local/bin/stata-se"

The StataSession$new() function returns an object that can be used to interact with the launched Stata session.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
n <- StataSession$new()
n$eval("local a = 1")
#> . local a = 1
n$eval("local b = 1")
#> local b = 1
n$eval("di `a' + `b'")
#> di `a' + `b'
#> 2

n$state()
#> [1] "running"
n$kill()
#> [1] TRUE
n$state()
#> [1] "terminated"

Using {statarepl} to launch a Stata terminal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stata_repl()

#> ── Welcome to Stata REPL ───────────────────────────────────────────────
#> Press ESC to quit
#> stata > clear all

#> Notes:
#> 1. Stata is running in batch mode.
#> 2. Unicode is supported; see help unicode_advice.
#> 3. Maximum number of variables is set to 5000; see help set_maxvar.

#> running /Applications/Stata15/profile.do ...

#> stata . clear all

#> .
#> stata .

Knitr

{statarepl} comes with a knitr engine that can be set with
statarepl::set_stata_engine() at the top of your markdown.

Then, each chunck {stata} will be evaluated in a Stata session.

You’ll find an example in inst/rmdexample.Rmd

Alter knitring, the result should be:

Acknowledgement

The codes in this project all comes from bubble, I still can’t understand all.

# R, Stata

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×