-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstata-in-rmarkdown.Rmd
105 lines (68 loc) · 2.36 KB
/
stata-in-rmarkdown.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
---
title: "Stata with Rmarkdown"
subtitle: ""
author: "Ihsan Fadilah"
institute: ""
date: "Last updated on `r Sys.Date()`"
output:
xaringan::moon_reader:
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
css: [metropolis-fonts]
editor_options:
chunk_output_type: console
---
class: middle, center
# Setup
---
Familiarity with **Rmarkdown** is assumed. In order to run **Stata** directly from within **Rmarkdown**, you need to run the following code chunk. Note that this only works if you have **Stata** already installed in your own machine.
```{r setup, warning = FALSE, message = FALSE}
# Package
library(Statamarkdown)
# Path to the executable Stata (machine-specific)
statapath <- "/Applications/Stata/StataIC.app/Contents/MacOS/StataIC"
# Set the Stata engine
knitr::opts_chunk$set(engine.path = list(stata = statapath))
```
To find your own path to the executable **Stata**:
1. Open **Stata**
1. Type `sysdir` in the Stata command window
1. The output that says `STATA:` indicates where the path is
1. Put the additional argument as shown in the code chunk above
I am using **StataIC** on a Mac, hence the path. Adjust the path accordingly since you may have a different version of **Stata** or operation system.
After all that, executing **Stata** code in **Rmarkdown** would be the same as if you worked in **R**. However, you need to specify the code chunk as follows.
` ```{stata} Your code``` `
---
class: middle, center
# Stata code with output
---
# Summarise data
```{stata, collectcode = TRUE}
sysuse auto, clear // Read in the data
summarize // Summarise data
```
To carry over the results from this code (e.g. loaded dataset) in subsequent operations, we need to specify the code chunk as follows.
` ```{stata, collectcode = TRUE} Your code``` `
---
# Univariable linear regression
```{stata}
regress price mpg
```
---
# Plot
```{stata, results = "hide"}
graph box mpg, over(foreign) // Box plot
// Save the plot to show as follows (not a direct output)
graph export "boxplot.svg", replace
```
<p align="center">
<img src = "boxplot.svg">
</p>
---
class: middle, center
# Any questions?
#### [email protected]
#### Reference ~ [Stata and R Markdown: the Statamarkdown package](https://www.ssc.wisc.edu/~hemken/Stataworkshops/stata.html#stata-and-r-markdown)