dplyr
basicsdplyrDuring ANLY 512 we will be studying the theory and practice of
data visualization. We will be using R and the
packages within R to assemble data and construct many
different types of visualizations. Before we begin studying data
visualizations we need to develop some data wrangling skills. We will
use these skills to wrangle our data into a form that we can use for
visualizations.
The objective of this assignment is to introduce you to R Studio,
Rmarkdown, the tidyverse and more specifically the dplyr
package.
Each question is worth 5 points.
To submit this homework you will create the document in Rstudio, using the knitr package (button included in Rstudio) and then submit the document to your Rpubs account. Once uploaded you will submit the link to that document on Canvas. Please make sure that this link is hyper linked and that I can see the visualization and the code required to create it.
Question #1
Use the nycflights13 package and the flights data frame to answer the following questions: a.What month had the highest proportion of cancelled flights? Cancelled flights are flights with no departure time. February has the highest proportion of canceled flights b.What month had the lowest? October
library(nycflights13)
data <- nycflights13::flights
data_tab <-
data %>%
group_by(month) %>%
summarise(cancelled = sum(is.na(dep_time)),
percent_cancelled = (cancelled/n()) *100) %>%
arrange(desc(percent_cancelled))
data_tab
## # A tibble: 12 x 3
## month cancelled percent_cancelled
## <int> <int> <dbl>
## 1 2 1261 5.05
## 2 12 1025 3.64
## 3 6 1009 3.57
## 4 7 940 3.19
## 5 3 861 2.99
## 6 4 668 2.36
## 7 5 563 1.96
## 8 1 521 1.93
## 9 8 486 1.66
## 10 9 452 1.64
## 11 11 233 0.854
## 12 10 236 0.817
#February has the highest proportion of canceled flights
#October has the lowest proportion of canceled flights
Question #2
Consider the following pipeline:
library(tidyverse)
# mtcars %>%
# group_by(cyl) %>%
# summarize(avg_mpg = mean(mpg)) %>%
# filter(am == 1)
#fixed code
mtcars %>%
group_by(cyl, am) %>%
summarize(avg_mpg = mean(mpg)) %>%
filter(am == 1)
## # A tibble: 3 x 3
## # Groups: cyl [3]
## cyl am avg_mpg
## <dbl> <dbl> <dbl>
## 1 4 1 28.1
## 2 6 1 20.6
## 3 8 1 15.4
What is the problem with this pipeline? The original code returned
the error “error in filter(): ! Problem while computing
..1 = am == 1. Caused by error in
mask$eval_all_filter(): ! object ‘am’ not found”
The “am” column either needs to be added to the group by() verb, or the filter() verb will need to be placed before the summarize() verb
Question #3
Define two new variables in the Teams data frame in the
pkg Lahman() package.
batting average (BA). Batting average is the ratio of hits (H) to at-bats (AB)
slugging percentage (SLG). Slugging percentage is total bases divided by at-bats (AB). To compute total bases, you get 1 for a single, 2 for a double, 3 for a triple, and 4 for a home run.
library(Lahman)
Teams <- Teams
Teams_2 <-
Teams %>%
mutate(BA =H/AB,
SLG = (H + X2B * 2 + X3B * 3 + HR * 4)/AB)
names(Teams_2)
## [1] "yearID" "lgID" "teamID" "franchID"
## [5] "divID" "Rank" "G" "Ghome"
## [9] "W" "L" "DivWin" "WCWin"
## [13] "LgWin" "WSWin" "R" "AB"
## [17] "H" "X2B" "X3B" "HR"
## [21] "BB" "SO" "SB" "CS"
## [25] "HBP" "SF" "RA" "ER"
## [29] "ERA" "CG" "SHO" "SV"
## [33] "IPouts" "HA" "HRA" "BBA"
## [37] "SOA" "E" "DP" "FP"
## [41] "name" "park" "attendance" "BPF"
## [45] "PPF" "teamIDBR" "teamIDlahman45" "teamIDretro"
## [49] "BA" "SLG"
Question #4
Using the Teams data frame in the
pkg Lahman() package. display the top-5 teams ranked in
terms of slugging percentage (SLG) in Major League Baseball history.
Repeat this using teams since 1969. Slugging percentage is total bases
divided by at-bats.To compute total bases, you get 1 for a single, 2 for
a double, 3 for a triple, and 4 for a home run.
library(Lahman)
#Top-5 teams ranked in terms of slugging percentage (SLG) in Major League Baseball history
Teams_3 <-
Teams_2 %>%
select(name, SLG) %>%
group_by(name) %>%
arrange(desc(SLG)) %>%
head(5)
Teams_3
## # A tibble: 5 x 2
## # Groups: name [5]
## name SLG
## <chr> <dbl>
## 1 Houston Astros 0.609
## 2 Minnesota Twins 0.607
## 3 Boston Red Sox 0.603
## 4 New York Yankees 0.600
## 5 Atlanta Braves 0.596
#Top-5 teams ranked in terms of slugging percentage (SLG) in Major League Baseball history since 1969
Team_4 <-
Teams_2 %>%
select(yearID, name, SLG) %>%
filter(yearID >= 1969) %>%
arrange(desc(SLG)) %>%
head(5)
Team_4
## yearID name SLG
## 1 2019 Houston Astros 0.6092998
## 2 2019 Minnesota Twins 0.6071179
## 3 2003 Boston Red Sox 0.6033975
## 4 2019 New York Yankees 0.5996776
## 5 2020 Atlanta Braves 0.5964320
Question #5
Use the Batting, Pitching, and
People tables in the pkg Lahman() package to
answer the following questions.
a.Name every player in baseball history who has accumulated at least 300 home runs (HR) and at least 300 stolen bases (SB). You can find the first and last name of the player in the Master data frame. Join this to your result along with the total home runs and total bases stolen for each of these elite players.
Similarly, name every pitcher in baseball history who has accumulated at least 300 wins (W) and at least 3,000 strikeouts (SO).
Identify the name and year of every player who has hit at least 50 home runs in a single season. Which player had the lowest batting average in that season?
library(Lahman)
#Players who have accumulated at least 300 home runs (HR) and at least 300 stolen bases (SB)
Batting_2 <-
Batting %>%
group_by(playerID)%>%
summarize(total_HR = sum(HR),
total_SB = sum(SB)) %>%
filter(total_HR >= 300 & total_SB >= 300) %>%
left_join(People, by = c('playerID' = 'playerID')) %>%
select(nameFirst, nameLast, total_HR, total_SB) %>%
arrange(desc(total_HR))
Batting_2
## # A tibble: 8 x 4
## nameFirst nameLast total_HR total_SB
## <chr> <chr> <int> <int>
## 1 Barry Bonds 762 514
## 2 Alex Rodriguez 696 329
## 3 Willie Mays 660 338
## 4 Andre Dawson 438 314
## 5 Carlos Beltran 435 312
## 6 Bobby Bonds 332 461
## 7 Reggie Sanders 305 304
## 8 Steve Finley 304 320
#Pitchers in baseball history who have accumulated at least 300 wins (W) and at least 3,000 strikeouts (SO).
Pitching_2 <-
Pitching %>%
group_by(playerID)%>%
summarize(total_W = sum(W),
total_SO = sum(SO)) %>%
filter(total_W >= 300 & total_SO >= 3000) %>%
left_join(People, by = c('playerID' = 'playerID')) %>%
select(nameFirst, nameLast, total_W , total_SO) %>%
arrange(desc(total_W))
Pitching_2
## # A tibble: 10 x 4
## nameFirst nameLast total_W total_SO
## <chr> <chr> <int> <int>
## 1 Walter Johnson 417 3509
## 2 Greg Maddux 355 3371
## 3 Roger Clemens 354 4672
## 4 Steve Carlton 329 4136
## 5 Nolan Ryan 324 5714
## 6 Don Sutton 324 3574
## 7 Phil Niekro 318 3342
## 8 Gaylord Perry 314 3534
## 9 Tom Seaver 311 3640
## 10 Randy Johnson 303 4875
#Name and year of every player who have hit at least 50 home runs in all recorded seasons.
Batting_3 <-
Batting %>%
group_by(playerID, yearID)%>%
summarize(total_HR = sum(HR),
batting_avg = sum(H)/sum(AB)) %>%
filter(total_HR >= 50) %>%
left_join(People, by = c('playerID' = 'playerID')) %>%
select(yearID, nameFirst, nameLast, total_HR, batting_avg) %>%
arrange(batting_avg)
Batting_3
## # A tibble: 46 x 6
## # Groups: playerID [30]
## playerID yearID nameFirst nameLast total_HR batting_avg
## <chr> <int> <chr> <chr> <int> <dbl>
## 1 alonspe01 2019 Pete Alonso 53 0.260
## 2 bautijo02 2010 Jose Bautista 54 0.260
## 3 jonesan01 2005 Andruw Jones 51 0.263
## 4 marisro01 1961 Roger Maris 61 0.269
## 5 vaughgr01 1998 Greg Vaughn 50 0.272
## 6 mcgwima01 1997 Mark McGwire 58 0.274
## 7 fieldce01 1990 Cecil Fielder 51 0.277
## 8 mcgwima01 1999 Mark McGwire 65 0.278
## 9 stantmi03 2017 Giancarlo Stanton 59 0.281
## 10 judgeaa01 2017 Aaron Judge 52 0.284
## # ... with 36 more rows
#Name and year of every player who hit at least 50 home runs in the 2001 season
Batting_4 <-
Batting %>%
group_by(playerID, yearID, HR)%>%
summarize(batting_avg = sum(H)/sum(AB)) %>%
filter(HR >= 50 & yearID == 2001) %>%
left_join(People, by = c('playerID' = 'playerID')) %>%
select(yearID, nameFirst, nameLast, HR, batting_avg)
Batting_4
## # A tibble: 4 x 6
## # Groups: playerID, yearID [4]
## playerID yearID nameFirst nameLast HR batting_avg
## <chr> <int> <chr> <chr> <int> <dbl>
## 1 bondsba01 2001 Barry Bonds 73 0.328
## 2 gonzalu01 2001 Luis Gonzalez 57 0.325
## 3 rodrial01 2001 Alex Rodriguez 52 0.318
## 4 sosasa01 2001 Sammy Sosa 64 0.328
#Players who have the lowest batting average in the 2001 Season - So many players had 0 batting average in the 2001 season
Batting_5 <-
Batting %>%
group_by(playerID, yearID)%>%
summarize(batting_avg = sum(H)/sum(AB)) %>%
filter(yearID == 2001) %>%
left_join(People, by = c('playerID' = 'playerID')) %>%
select(nameFirst, nameLast, batting_avg) %>%
arrange(batting_avg)
Batting_5
## # A tibble: 1,220 x 4
## # Groups: playerID [1,220]
## playerID nameFirst nameLast batting_avg
## <chr> <chr> <chr> <dbl>
## 1 abadan01 Andy Abad 0
## 2 aldrico01 Cory Aldridge 0
## 3 ankieri01 Rick Ankiel 0
## 4 arrojro01 Rolando Arrojo 0
## 5 atchlju01 Justin Atchley 0
## 6 baezbe01 Benito Baez 0
## 7 barteki01 Kimera Bartee 0
## 8 beckro01 Rod Beck 0
## 9 belitto01 Todd Belitz 0
## 10 benitar01 Armando Benitez 0
## # ... with 1,210 more rows