Week 2

Data Wrangling and Visualization

Author

Prof. Jack Reilly

Published

Fall 2026

Assignment 2 Solutions

Download answers to Assignment 2 Here

dwv_ps2_solutions.R
#Title: DWV Week 2 Solutions
#Author: Jack Reilly
#Purpose: Solutions for Week 2 Assignment
#Requires: npsvisitation0910.csv - class dataset
#Output: Nothing

#1. Roll a 12 sided die 50 times. Store the result in an object roll. What is the mean (average) of your 10 die rolls?
roll<-sample(1:12, size = 50, replace = T); mean(roll)

#2. Create a object named trusttheforce.

name<-c("Luke", "Han", "Leia", "Vader", "Rey")
force<-c(T, F, T, T, T)
sith<-c(F, F, F, T, F)
movies<-c(5, 4, 6, 6, 3)

trusttheforce <- data.frame(name, force, sith, movies)

#3. Draw a histogram of movies.

hist(trusttheforce$movies)

#4. Replace Vader's number of movies with 4.
#There are two ways to do this.  
#One way would be to make a new variable, which you could then rebind into a dataframe:

moviesobiwan<-c(4, 4, 6, 6, 3)

#A better way is to directly replace the 4th column, 4th row.

View(trusttheforce)
trusttheforce[4,4]

trusttheforce[4,4]<-4

trusttheforce[4,4]

hist(trusttheforce$movies)

#5. Load npsvisitation0910.csv.
#What is the average number of park visitors in 2009? 2010?

nps<-read.csv("/Users/reillyj/Desktop/working/dwv/npsvisitation0910.csv")
mean(nps$year2009)
mean(nps$year2010)

#6. Consider Yellowstone and Mt Rainier National Parks.

#How many more visitors did each park, individually, have in 2010 compared to 2009?
#If you just want to look at the numbers:
nps[359,2]
nps[359,3]

#Yellowstone
nps[359,3]-nps[359,2]

#Rainier
nps[235,3]-nps[235,2]

#What is the difference in the number of visitors between those two parks in 2009? (Subtract one cell from the other)
nps[359,2]-nps[235,2]

#How many visitors did the parks have, combined, in 2010? (Add one cell to the other)
nps[359,3]+nps[235,3]

#BONUS: Roll one twelve sided die 1000 times. 
#Then, roll two six sided dice (together) 1000 times. 
#Add the two six sided die rolls together, so you can get a β€œcombined” roll that goes from 2 to 12 (the way you would in a normal board game). 
#What is the mean of the twelve sided die rolls and two six sided dice rolls? How do the distributions (histogram) of these two rolls differ?

die1<-sample(1:6, size = 1000, replace = T)
die2<-sample(1:6, size = 1000, replace = T)

rollsixes<-die1+die2

rolltwelve<-sample(2:12, size = 1000, replace = T)

mean(rollsixes)
mean(rolltwelve)

sd(rollsixes)
sd(rolltwelve)

hist(rollsixes)
hist(rolltwelve)

#That's ugly. Let's load a different *library* and use a different histogram command

library(lattice)

histogram(rollsixes)
histogram(rolltwelve)

Quarto Workshop

Find the quarto workshop here