---
title: "Empirical Project 7: Working in R code"
---
# Empirical Project 7 Working in R
These code downloads have been constructed as supplements to the full Doing Economics projects (https://core-econ.org/doing-economics/). You'll need to download the data before running the code that follows.
## Getting started in R
For this project you will need the following packages:
- `tidyverse`, to help with data manipulation
- `readxl`, to import an Excel spreadsheet.
If you need to install either of these packages, run the following code:
```{r}
install.packages(c("readxl","tidyverse"))
```
You can import the libraries now, or when they are used in the R walk-through below.
```{r}
library(readxl)
library(tidyverse)
```
## Part 7.1 Drawing supply and demand diagrams
### R walk-through 7.1 Importing data into R and creating tables and charts
First we import the data with the `read_excel` function, using the `na = "NA"` option to indicate how missing data is recorded.
```{r}
library(tidyverse)
```
```{r}
library(readxl)
# Set working directory
setwd("YOURFILEPATH")
wm_data <- read_excel("Project 7 datafile.xlsx",
sheet = "Sheet1", na = "NA")
str(wm_data)
```
Let's use the `exp` function to create the variables `p` and `q` from their log counterparts (renamed as `log.p` and `log.q` respectively). We also transform the harvest variable (renamed as `log.h`) and save it as `h`. The harvest will be at most as large as the crop (`q`).
```{r}
names(wm_data) <- c("Year", "log.q", "log.h", "log.p",
"log.pc", "log.pv", "log.w", "log.n", "log.yn", "log.pf")
wm_data$p <- exp(wm_data$log.p) # Price
wm_data$h <- exp(wm_data$log.h) # Harvest quantity
wm_data$q <- exp(wm_data$log.q) # Crop quantity
```
Let's use `plot` to produce the chart for the prices, with `Year` as the horizontal axis variable (`xlab`) and price (`p`) as the vertical axis variable (`ylab`).
```{r}
# type: "p" = points, "l" = lines, "o" = points and lines
plot(wm_data$Year, wm_data$p, type = "o",
xlab = "Year", ylab = "Price")
```
Now we create the line chart for harvest and crop quantities (the variables `h` and `q`, respectively). First, we plot the crop quantities as a dashed line (`lty = "dashed"`), then use `lines` to add a solid line for the harvest data. The `legend` function adds a chart legend at the specified coordinates (the first two arguments in the function).
```{r}
# type: "p" = points, "l" = lines, "o" = points and lines
plot(wm_data$Year, wm_data$q, type = "o",
pch = 1, lty = "dashed",
xlab = "Year", ylab = "Price")
# Add the harvest data
lines(wm_data$Year, wm_data$h, type = "o", pch = 16)
# Add a legend
legend(1947.5, 55, legend = c("Crop", "Harvest"),
col = c("black", "black"), pch = c(1, 16),
lty = c("dashed", "solid"), cex = 0.8)
```
[End of walk-through]