The file you are reading is called an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com. The way you can create a file like this in RStudio is: File → New File → R Markdown and then using the default or using a template.
The gray area below is a code chunk that will set up our packages and data. You can also run the code within the editor area by pressing the green play button. Don’t worry right now about what the code is doing, we will cover this later. We just want you to get used to RStudio and RMarkdowns. This dataset is one we’ll be working with quite a lot in the lectures. It contains county-level data about ER visits for heat-related illnesses in Colorado for the years 2011-2022.
library(tidyverse)
er <- read_csv(file = "https://daseh.org/data/CO_ER_heat_visits.csv")
# keep non-missing data
er_2 <- er %>%
filter(!is.na(rate))
When you click the Knit button (at the top of RStudio), a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. Note that when it does this it starts from scratch - it can’t use any objects you created outside of the Rmd file. Therefore it essentially has its own environment that is different from the one that you see when working interactively in RStudio.
Here is code that will make a plot of some data.
Try the “run all chunks above” button that is to the left of the play button on the following chunk. What happens?
Then press the play button on this same chunk. What happens?
# keep only some counties
er_3 <- er_2 %>%
filter(county %in% c("Arapahoe", "Denver", "Jefferson", "Larimer"))
palette <- c(
Arapahoe = "red",
Denver = "darkgreen",
Jefferson = "orange",
Larimer = "salmon"
)
ggplot(aes(x = year, y = rate, colour = county, group = county), data = er_3) +
geom_line() +
scale_colour_manual(values = palette)
<!-- Your code chunk goes here -->
. You can use the insert chunk button or copy paste an existing code chunk. Include a lowercase x inside the chunk as the code. Make sure you press the knit button after this to see what the new chunk looks like.x <- c(1, 2, 3)
x
## [1] 1 2 3
Here are a few changes that will show you how to change small things in R
code and the output it makes. After each change, hit the Knit button again.
Go through the code for the plot above and change the colors in palette
to something other than what they originally were. See http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf for a large list of colors. For example, you could replace blue with red.
Create another R Markdown Document from RStudio dropdowns: File → New File → R Markdown.
Add a new header with two hash symbols ##
at the start of a line with some text. Knit the report to see how it looks.