Chapter 8 Minihacks
Minihacks are practice problems for you to challenge yourself and learn the material more deeply. Give them a shot!
8.1 Minihack 1: R Markdown
Create an
R Markdown
document calledminihacks
. Save it in yourtools
->scripts
folder.Try rendering your
R Markdown
document by clickingknit
. If it doesn’t render correctly, try to figure out why it didn’t.
8.2 Minihack 2: Arithmetic Commands
Use R to calculate \(\frac{(102 + 68) \times (3 + 2) + 1250}{50}\) and assign the result to a variable called
x
.Assign the numbers
10
,20
, and30
to a vector calledy
.Before running any code, determine what you think adding
x
toy
would result in. Then, using R, addx
toy
.
8.3 Minihack 3: Functions
Assign the string
"I AM NOT YELLING"
to a variable calledexclamation
.Use the function
tolower()
to convert every letter ofexclamation
to lower case. Assign the result toexclamation
.Use the
capitalize()
function from theHmisc
package to capitalize the first letter ofexclamation
.
8.4 Minihack 4: Help Documentation
- I wanted to create a vector of
5
values between10
and50
usingseq()
, but the code I wrote is creating a vector of9
values between10
and50
. I believe it has something to do with the arguments I used, but I can’t remember how to access the help documention to check. Without changing the values (i.e.,10
,50
, and5
), can you fix my code?
## [1] 10 15 20 25 30 35 40 45 50
8.5 Minihack 5: Data Frames
Download the Marvel character dataset to your computer. Put the data file in your
tools
->data
folder.Import the data into R and assign it to a variable called
marvel_data
.Ah! The value for the number of appearances of Spider-Man seems to be an error! It should be
4043
not40430
! Use square brackets ([]
) to replace the erroneous value with the correct value (hint: The value is stored in the first row of the eighth column).Using
mean()
and dollar sign notation (data$column
), calculate the average number of appearances for all of the Marvel characters. Assign the result to a variable calledmean_appearances
.Install and load the package
ggplot2
.If you succesfully completed the proceeding steps, you should be able to run the following code without producing an error. If you get an error, try to figure out why you are receiving the error.
ggplot(marvel_data, aes(x = reorder(align, -appearances),
y = appearances,
fill = align)) +
geom_bar(stat = "summary", fun.y = "mean") +
geom_point(shape = 21,
alpha = .7,
position = position_jitter(w = 0.4, h = 0)) +
geom_hline(yintercept = mean_appearances,
linetype = "twodash",
lwd = 1,
colour = "firebrick") +
annotate(geom = "text",
x = 3,
y = 800,
size = 5,
label = paste("Mean = ", round(mean_appearances, 2)),
colour = "firebrick") +
scale_fill_viridis_d() +
theme_bw(base_size = 15) +
theme(legend.position = "none") +
labs(title = "Alignment and Appearances",
subtitle = "Marvel character appearances by alignment",
x = "Alignment",
y = "Appearances")