4  :blue_book: From Stata to R

To reduce the learning curve and associated costs of transitioning from Stata to R, it can be helpful for Stata users to know that they can execute Stata commands within R programmes, allowing them to interleave Stata and R commands seamlessly.

To call Stata within R, you need a Stata installation on your laptop. You need to install the RStata R package, which is a simple R / Stata interface that enables you to:

```{r}
if ( !require(RStata) ) {
  install.packages('RStata')
}
library(RStata)
```

4.1 Configure RStudio to execute Stata

4.1.1 Find your Stata binary path

The function chooseStataBin from the RStata library allows you to browse and set the path to your Stata binary executable.

```{r}
stata_bin_path <- RStata::chooseStataBin()
```
```{r}
print(stata_bin_path)
```

When you run this code, you should normally get a path which is of the format: “"C:\Program Files\Stata16\StataIC-64"”. Note that the .exe extension has been removed from this path. It is important that you keep the format as is, as otherwise your Stata engine will not be recognised.

4.1.2 Add your Stata binary path to your .Rprofile

The Stata binary path setting we just created is just for your current RStudio session and it will be lost once your RStudio is closed. To keep this setting each time you are using RStudio and avoid havin to reconfigure RStata each time you are restarting RStudio, let us add the Stata binary path as an option to .Rprofile, which is your user-specific R configuration file.

library(usethis)
Note

usethis is a workflow package: it automates repetitive tasks that arise during project setup and development, both for R packages and non-package projects.

The function edit_r_profile from the usethis library allows to open your configuration file .Rprofile.

```{r}
usethis::edit_r_profile("user")
```

Add the following two lines in the Rprofile file that you have just opened:

```{r}
options("RStata.StataPath" = ...)
options("RStata.StataVersion" = ...)
```

You need to indicate the path to your Stata binary executable in the RStata.StataPath option (e.g., “"C:\Program Files\Stata16\StataIC-64"”) and the version of your Stata (e.g., 16) in the RStata.StataVersion option.

after indicating the path and version your code should look as specified below

```{r}
options("RStata.StataPath" = "\"C:\\Program Files (x86)\\Stata15\\Stata-64\"")
options("RStata.StataVersion" = 15)
```

Once you are done, save and close your .Rprofile.