In this assignment you will need to solve a series of programming questions about R using RStudio. You are encourages to look up the official documentation.
RMarkdown at its core
is a combination of R and Markdown used
to generate reproducible reports for data analyses.
Your goal is to run all the cells below one by one from top to bottom. Before you run some code chunks, you need to complete the missing code (indicated by the NA) in them.
For each task chunk that requires your completion, you should run it to check if your code is correct. The cell output should be similar to the “expected output” that follows.
include = FALSE prevents code and results from
appearing in the finished file. R Markdown still runs the code in the
chunk, and the results can be used by other chunks.echo = FALSE prevents code, but not the results from
appearing in the finished file. This is a useful way to embed
figures.message = FALSE prevents messages that are generated by
code from appearing in the finished file.warning = FALSE prevents warnings that are generated by
code from appearing in the finished.The ? code pulls up documentation of a function. This
will spawn a browser window when knitting, or potentially crash during
knitting.
help("sqrt")
?sqrt # Same thing
help.search("chi square")
??"chi square" # Same thing
When using RMarkdown, any time you knit your document to its
final form, say .html, a number of programs run in the
background. Your current R environment seen in RStudio will
be reset. Any objects you created while working interactively inside
RStudio will be ignored. Essentially a new R session will
be spawned in the background and the code in your document is run there
from start to finish. For this reason, things such as importing data
must be explicitly coded into your document.
# Install and load packages in a single line for each
if (!require("tinytex")) install.packages("tinytex"); library("tinytex")
Loading required package: tinytex
if (!require("readr")) install.packages("readr"); library("readr")
Loading required package: readr
if (!require("rmarkdown")) install.packages("rmarkdown"); library("rmarkdown")
Loading required package: rmarkdown
Registered S3 methods overwritten by 'htmltools':
method from
print.html tools:rstudio
print.shiny.tag tools:rstudio
print.shiny.tag.list tools:rstudio
if (!require("ggplot2")) install.packages("ggplot2"); library("ggplot2")
Loading required package: ggplot2
if (!require("xtable")) install.packages("xtable"); library("xtable")
Loading required package: xtable
if (!require("pander")) install.packages("pander"); library("pander")
Loading required package: pander
The following generates a random plot.
# Generate random data
x <- runif(100) # 100 random values between 0 and 1 for x-axis
y <- runif(100) # 100 random values between 0 and 1 for y-axis
# Basic scatter plot of random dots
plot(x, y)
The following generates a sad plot.
# Create data for the face, eyes, and frown
face <- data.frame(x = 0, y = 0)
eyes <- data.frame(x = c(-0.3, 0.3), y = c(0.3, 0.3))
frown <- data.frame(x = -cos(seq(pi, 2 * pi, length.out = 100)) / 2, y = -sin(seq(pi, 2 * pi, length.out = 100)) / 2 - 0.5)
# Plotting the smiley face
ggplot() +
geom_point(data = face, aes(x = x, y = y), color = "yellow", size = 70) +
geom_point(data = eyes, aes(x = x, y = y), color = "black", size = 5) +
geom_line(data = frown, aes(x = x, y = y), color = "black", size = 1) +
coord_fixed(ratio = 1) +
theme_void() +
xlim(-1.5, 1.5) +
ylim(-2.5, 2.5)
Install the maps package:
if (!require("maps")) install.packages("maps"); library("maps")
Loading required package: maps
The maps package contains spatial information at various
levels (national, regional, etc) that allows us to plot mapping data
using the Geom geom_polygon.
# Get the latitude and longitude coordinate for mainland America:
usa <- map_data("usa")
# Plot these using geom_polygon
gg1 <- ggplot() +
geom_polygon(data = usa, aes(x = long, y = lat, group = group), fill = "violet", color = "blue") +
coord_fixed(1.3)
gg1
Let’s assume the following coordinates for these cities:
San Diego: Latitude 32.7157° N, Longitude -117.1611° W
New York: Latitude 40.7128° N, Longitude -74.0060° W
# Now, let's plot the coordinates on our map
gg1 <- gg1 +
geom_point(aes(x = -117.1611, y = 32.7157), color = "red", size = 3) +
geom_text(aes(x = -117.1611, y = 32.7157, label = "San Diego"), vjust = -1) +
geom_point(aes(x = -74.0060, y = 40.7128), color = "green", size = 3) +
geom_text(aes(x = -74.0060, y = 40.7128, label = "New York"), vjust = -1)
gg1
Do you see how this works? Look at the usa data frame
and it is just a collection of coordinates defining the outline of the
country. In this code, geom_point() adds
the points for each city, and geom_text()
optionally adds labels near the points. The
vjust parameter in
geom_text() adjusts the vertical position
of the labels to avoid overlapping with the points. You can customize
the colors and sizes as needed.
We use the ggplot() function to build plots. Notice that
the command geom_polygon looks like a function, with
arguments separated by commas.
data = usaaesthetic elements of the plot, e.g. the x and the y axes,
along with some colors.+ to
specify the geometric object for the plot.
geom_point.geom_polygonYou might wonder how you are supposed to know the syntax for the
ggplot function. Thankfully, R documents all of its
functions extensively. To read what a function does and learn the
arguments that are available to you, just type in a question mark
followed by the name of the function that you’re interested in. Try the
following in your console: ?ggplot
Assume the following coordinates for these cities:
################START CODE HERE##############
# Replace NA with
gg1 <- gg1 +
geom_point(NA) +
geom_text(NA) +
geom_point(NA) +
geom_text(NA)
################END CODE HERE################
gg1
################START CODE HERE##############
# Adding points for Austin and Miami
gg1 <- gg1 +
geom_point(aes(x = -97.7431, y = 30.2672), color = "blue", size = 3) +
geom_text(aes(x = -97.7431, y = 30.2672, label = "Austin"), vjust = -1) +
geom_point(aes(x = -80.1918, y = 25.7617), color = "orange", size = 3) +
geom_text(aes(x = -80.1918, y = 25.7617, label = "Miami"), vjust = -1)
################END CODE HERE################
gg1
We use the sample() function in R to simulate the
rolling of a six-sided die. The sample() function randomly
selects elements from a specified vector, which in this case will be the
numbers 1 through 6.
# Sequence from 1 to 6
sides_six <- 1:6
# Simulate rolling the six-sided die 10 times
rolls_six <- sample(sides_six, 10, replace = TRUE)
# Compute and print the average of the rolls
average_roll_six <- mean(rolls_six)
print(average_roll_six)
[1] 3.2
Now, we’ll use this frequency data to create a bar chart.
roll_frequencies <- table(rolls_six)
# Create a bar chart of roll frequencies
ggplot(data = as.data.frame(roll_frequencies), aes(x = rolls_six, y = Freq)) +
geom_bar(stat = "identity", fill = "blue", color = "black") +
labs(title = "Frequency of Rolls for a Six-Sided Die",
x = "Die Face",
y = "Frequency") +
theme_minimal()
Modify the setup code to simulate:
The rolling of a tetrahedron die (4-sided die)
Rolling the tetrahedron 20 times.
Plotting the bar chart
################START CODE HERE##############
sides_tetra <- NA # Sequence from 1 to 4
rolls_tetra <- NA # roll the four-sided die 20 times
average_roll_tetra <- NA # Compute the average
################END CODE HERE################
print(average_roll_tetra)
[1] NA
################START CODE HERE##############
# Four-sided die labeled from 1 to 4
sides_tetra <- 1:4
# Simulate rolling the four-sided die 20 times
rolls_tetra <- sample(sides_tetra, 20, replace = TRUE)
# Compute and print the average of the rolls
average_roll_tetra <- mean(rolls_tetra)
################END CODE HERE################
print(average_roll_tetra)
[1] 2.25
Now, the bar chart.
################START CODE HERE##############
tetra_roll_frequencies <- NA
################END CODE HERE################
ggplot(data = as.data.frame(tetra_roll_frequencies), aes(x = rolls_tetra, y = Freq)) +
geom_bar(stat = "identity", fill = "blue", color = "black") +
labs(title = "Frequency of Rolls for a Four-Sided Die",
x = "Die Face",
y = "Frequency") +
theme_minimal()
Once again we use the sample() function to a six-sided
die. Additionally, we will count how often the roll is exactly 6 with
sum(die_rolls == 6). Finally, repeat the experiment of
rolling a six-sided die 10 times-1000 times. Calculate how many times a
six occurs at least once in these 10 rolls across all experiments.
n = 1000 # number of trials
six_sides = 1:6 # Six-sided die
six_count.sim <- numeric(n) # variables names can contain a period.
for (simnum in 1:n) {
roll = sample(six_sides, 10, replace = TRUE) # Roll the die ten times
six_count.sim[simnum] = sum(roll == 6) # count the number of sixes
}
six_count.freq <- table(six_count.sim) # Frequency table of sixes count
six_count.avg <- mean(six_count.sim) # Average number of sixes per trial
six_count.freq
six_count.sim
0 1 2 3 4 5 6
173 322 258 160 69 17 1
six_count.avg
[1] 1.685
# Create a histogram using six_count.sim
ggplot(data = data.frame(CountOfSixes = six_count.sim), aes(x = CountOfSixes)) +
geom_histogram(bins = 10, fill = "skyblue", color = "black") +
labs(title = "Histogram of the Number of Sixes Rolled in Each Experiment",
x = "Number of Sixes in 10 Rolls",
y = "Frequency of Experiments") +
theme_minimal()
six_count.sim vector.aes(x = CountOfSixes) sets the x-axis to represent the
count of sixes.geom_histogram is used to plot the
histogram, with the bins parameter
allowing you to adjust the granularity of the histogram.geom_histogram are set
for aesthetic purposes.labs function is used to set the title
and axis labels x, y.six_count.sim is the
count of sixes from one of those thousand rounds.six_count.freq is a different
beast. It’s a summary. It takes all those notes and sorts them into
piles. Say, “Here’s how many experiments got no sixes, here’s how many
got one six, and so on.”In the previous experiment, you simulated rolling a six-sided die and counted the number of times you rolled a six. Now, let’s change this a bit.
Modify the setup code to simulate:
the rolling of a tetrahedron die (4-sided die)
15 times per trial
In each set of 15 rolls, count how many times you roll a 4.
Repeating this simulation for 10000 trials.
Generate a frequency table for the count of 4s and calculate the average number rolled per trial.
Create a histogram to display the distribution of the count of 4s across all trials.
# Start here...