Queer European MD passionate about IT

Mission376Solutions.Rmd 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. ---
  2. title: "Mission 376 Solutions"
  3. output: html_document
  4. ---
  5. ```{r}
  6. library(tidyverse)
  7. library(RSQLite)
  8. library(DBI)
  9. ```
  10. # Getting to Know the Data
  11. ```{r}
  12. # R has trouble guessing some column types, so we explicitly tell it
  13. # the types of the problem columns
  14. log <- read_csv("game_log.csv",
  15. col_types = cols(.default = "c",
  16. v_league = "c", h_league = "c",
  17. `3b_umpire_id` = "c", `3b_umpire_name` = "c",
  18. `2b_umpire_id` = "c", `2b_umpire_name` = "c",
  19. `lf_umpire_id` = "c", `lf_umpire_name` = "c",
  20. `rf_umpire_id` = "c", `rf_umpire_name` = "c",
  21. completion = "c", winning_rbi_batter_id = "c",
  22. winning_rbi_batter_id_name = "c", protest = "c",
  23. v_first_catcher_interference = "c",
  24. h_first_catcher_interference = "c"))
  25. head(log)
  26. ```
  27. ```{r}
  28. dim(log)
  29. ```
  30. It looks like the game log has a record of over 170,000 games. It looks like these games are chronologically ordered and occur between 1871 and 2016.
  31. For each game we have:
  32. * general information on the game
  33. * team level stats for each team
  34. * a list of players from each team, numbered, with their defensive positions
  35. * the umpires that officiated the game
  36. * some 'awards', like winning and losing pitcher
  37. We have a game_log_fields.txt file that tell us that the player number corresponds with the order in which they batted.
  38. It's worth noting that there is no natural primary key column for this table.
  39. ```{r}
  40. person <- read_csv("person_codes.csv")
  41. head(person)
  42. ```
  43. ```{r}
  44. dim(person)
  45. ```
  46. This seems to be a list of people with IDs. The IDs look like they match up with those used in the game log. There are debut dates, for players, managers, coaches and umpires. We can see that some people might have been one or more of these roles.
  47. It also looks like coaches and managers are two different things in baseball. After some research, managers are what would be called a 'coach' or 'head coach' in other sports, and coaches are more specialized, like base coaches. It also seems like coaches aren't recorded in the game log.
  48. ```{r}
  49. park <- read_csv("park_codes.csv")
  50. head(park)
  51. ```
  52. ```{r}
  53. dim(park)
  54. ```
  55. This seems to be a list of all baseball parks. There are IDs which seem to match with the game log, as well as names, nicknames, city and league.
  56. ```{r}
  57. team <- read_csv("team_codes.csv")
  58. head(team)
  59. ```
  60. ```{r}
  61. dim(team)
  62. ```
  63. This seems to be a list of all teams, with team_ids which seem to match the game log.
  64. ## Defensive Positions
  65. In the game log, each player has a defensive position listed, which seems to be a number between 1-10. Doing some research around this, I found this [article] (http://probaseballinsider.com/baseball-instruction/baseball-basics/baseball-basics-positions/) which gives us a list of names for each numbered position:
  66. * Pitcher
  67. * Catcher
  68. * 1st Base
  69. * 2nd Base
  70. * 3rd Base
  71. * Shortstop
  72. * Left Field
  73. * Center Field
  74. * Right Field
  75. The 10th position isn't included, it may be a way of describing a designated hitter that does not field. I can find a retrosheet page that indicates that position 0 is used for this, but we don't have any position 0 in our data. I have chosen to make this an 'Unknown Position' so I'm not including data based on a hunch.
  76. ## Leagues
  77. Wikipedia tells us there are currently two leagues - the American (AL) and National (NL). Upon investigation of the data, we see that there are actually 4 more. After some googling, we come up with:
  78. * NL: National League
  79. * AL: American League
  80. * AA: [American Association](https://en.wikipedia.org/wiki/American_Association_%2819th_century%29)
  81. * FL: [Federal League](https://en.wikipedia.org/wiki/Federal_League)
  82. * PL: [Players League](https://en.wikipedia.org/wiki/Players%27_League)
  83. * UA: [Union Association](https://en.wikipedia.org/wiki/Union_Association)
  84. It also looks like we have about 1000 games where the home team doesn't have a value for league.
  85. # Importing Data Into SQLite
  86. ```{r}
  87. conn <- dbConnect(SQLite(), "mlb.db")
  88. dbWriteTable(conn = conn, name = "game_log",
  89. value = log, row.names = FALSE, header = TRUE)
  90. dbWriteTable(conn = conn, name = "person_codes",
  91. value = person, row.names = FALSE, header = TRUE)
  92. dbWriteTable(conn = conn, name = "team_codes",
  93. value = team, row.names = FALSE, header = TRUE)
  94. dbWriteTable(conn = conn, name = "park_codes",
  95. value = park, row.names = FALSE, header = TRUE)
  96. # Confirm that all of the tables are in
  97. dbListTables(conn)
  98. ```
  99. ```{r}
  100. # Create the new column within game_log
  101. alter_game_log_command <- "
  102. ALTER TABLE game_log
  103. ADD COLUMN game_id TEXT;
  104. "
  105. dbExecute(conn, alter_game_log_command)
  106. # Use string concatenation to update this new column
  107. update_game_log_command <- "
  108. UPDATE game_log
  109. SET game_id = date || h_name || number_of_game
  110. /* WHERE prevents this if it has already been done */
  111. WHERE game_id IS NULL;
  112. "
  113. dbExecute(conn, update_game_log_command)
  114. # Make sure that your queries worked
  115. check_query_1 <- "
  116. SELECT
  117. game_id,
  118. date,
  119. h_name,
  120. number_of_game
  121. FROM game_log
  122. LIMIT 5;
  123. "
  124. check <- dbGetQuery(conn, check_query_1)
  125. head(check)
  126. ```
  127. # Looking for Normalization Opportunities
  128. The following are opportunities for normalization of our data:
  129. * In person_codes, all the debut dates will be able to be reproduced using game log data.
  130. * In team_codes, the start, end and sequence columns will be able to be reproduced using game log data.
  131. * In park_codes, the start and end years will be able to be reproduced using game log data. While technically the state is an attribute of the city, we might not want to have a an incomplete city/state table so we will leave this in.
  132. * There are lots of places in game log where we have a player ID followed by the players name. We will be able to remove this and use the name data in person_codes
  133. * In game_log, all offensive and defensive stats are repeated for the home team and the visiting team. We could break these out and have a table that lists each game twice, one for each team, and cut out this column repetition.
  134. * Similarly, in game_log, we have a listing for 9 players on each team with their positions - we can remove these and have one table that tracks player appearances and their positions.
  135. * We can do a similar thing with the umpires from game_log, instead of listing all four positions as columns, we can put the umpires either in their own table or make one table for players, umpires and managers.
  136. * We have several awards in game_log like winning pitcher and losing pitcher. We can either break these out into their own table, have a table for awards, or combine the awards in with general appearances like the players and umpires.
  137. # Creating Tables Without Foreign Keys
  138. ```{r}
  139. create_person_command <- "
  140. CREATE TABLE IF NOT EXISTS person (
  141. person_id TEXT PRIMARY KEY,
  142. first_name TEXT,
  143. last_name TEXT
  144. );
  145. "
  146. dbExecute(conn, create_person_command)
  147. insert_to_person <- "
  148. INSERT OR IGNORE INTO person
  149. SELECT
  150. id,
  151. first,
  152. last
  153. FROM person_codes;
  154. "
  155. dbExecute(conn, insert_to_person)
  156. check_query_2 <- "SELECT * FROM person LIMIT 5;"
  157. check <- dbGetQuery(conn, check_query_2)
  158. head(check)
  159. ```
  160. ```{r}
  161. create_park_command <- "
  162. CREATE TABLE IF NOT EXISTS park (
  163. park_id TEXT PRIMARY KEY,
  164. name TEXT,
  165. nickname TEXT,
  166. city TEXT,
  167. state TEXT,
  168. notes TEXT
  169. );
  170. "
  171. dbExecute(conn, create_park_command)
  172. insert_to_park <- "
  173. INSERT OR IGNORE INTO park
  174. SELECT
  175. park_id,
  176. name,
  177. aka,
  178. city,
  179. state,
  180. notes
  181. FROM park_codes;
  182. "
  183. dbExecute(conn, insert_to_park)
  184. check_query_3 <- "SELECT * FROM park LIMIT 5;"
  185. check_3 <- dbGetQuery(conn, check_query_3)
  186. ```
  187. ```{r}
  188. create_league_command <- "
  189. CREATE TABLE IF NOT EXISTS league (
  190. league_id TEXT PRIMARY KEY,
  191. name TEXT
  192. );
  193. "
  194. dbExecute(conn, create_league_command)
  195. insert_to_league <- '
  196. INSERT OR IGNORE INTO league
  197. VALUES
  198. ("NL", "National League"),
  199. ("AL", "American League"),
  200. ("AA", "American Association"),
  201. ("FL", "Federal League"),
  202. ("PL", "Players League"),
  203. ("UA", "Union Association")
  204. ;
  205. '
  206. dbExecute(conn, insert_to_league)
  207. check_query_4 <- "SELECT * FROM league"
  208. check <- dbGetQuery(conn, check_query_4)
  209. head(check)
  210. ```
  211. ```{r}
  212. appearance_drop_precaution <- "DROP TABLE IF EXISTS appearance_type;"
  213. dbExecute(conn, appearance_drop_precaution)
  214. appearance_type = read_csv('appearance_type.csv')
  215. dbWriteTable(conn = conn, name = "appearance_type",
  216. value = appearance_type,
  217. row.names = FALSE, header = TRUE)
  218. check_query_5 <- "SELECT * FROM appearance_type;"
  219. check <- dbGetQuery(conn, check_query_5)
  220. head(check)
  221. ```
  222. # Adding The Team and Game Tables
  223. ```{r}
  224. create_team_command <- "
  225. CREATE TABLE IF NOT EXISTS team (
  226. team_id TEXT PRIMARY KEY,
  227. league_id TEXT,
  228. city TEXT,
  229. nickname TEXT,
  230. franch_id TEXT,
  231. FOREIGN KEY (league_id) REFERENCES league(league_id)
  232. );
  233. "
  234. dbExecute(conn, create_team_command)
  235. insert_to_team <- "
  236. INSERT OR IGNORE INTO team
  237. SELECT
  238. team_id,
  239. league,
  240. city,
  241. nickname,
  242. franch_id
  243. FROM team_codes;
  244. "
  245. dbExecute(conn, insert_to_team)
  246. check_query_6 <- "SELECT * FROM team LIMIT 5;"
  247. check <- dbGetQuery(conn, check_query_6)
  248. head(check)
  249. ```
  250. ```{r}
  251. create_game_command <- "
  252. CREATE TABLE IF NOT EXISTS game (
  253. game_id TEXT PRIMARY KEY,
  254. date TEXT,
  255. number_of_game INTEGER,
  256. park_id TEXT,
  257. length_outs INTEGER,
  258. day BOOLEAN,
  259. completion TEXT,
  260. forefeit TEXT,
  261. protest TEXT,
  262. attendance INTEGER,
  263. legnth_minutes INTEGER,
  264. additional_info TEXT,
  265. acquisition_info TEXT,
  266. FOREIGN KEY (park_id) REFERENCES park(park_id)
  267. );
  268. "
  269. dbExecute(conn, create_game_command)
  270. insert_to_game <- '
  271. INSERT OR IGNORE INTO game
  272. SELECT
  273. game_id,
  274. date,
  275. number_of_game,
  276. park_id,
  277. length_outs,
  278. CASE
  279. WHEN day_night = "D" THEN 1
  280. WHEN day_night = "N" THEN 0
  281. ELSE NULL
  282. END
  283. AS day,
  284. completion,
  285. forefeit,
  286. protest,
  287. attendance,
  288. length_minutes,
  289. additional_info,
  290. acquisition_info
  291. FROM game_log;
  292. '
  293. dbExecute(conn, insert_to_game)
  294. check_query_7 <- "SELECT * FROM game LIMIT 5;"
  295. check <- dbGetQuery(conn, check_query_7)
  296. head(check)
  297. ```
  298. # Adding the Team Appearance Table
  299. ```{r}
  300. create_team_appearance_command <- "
  301. CREATE TABLE IF NOT EXISTS team_appearance (
  302. team_id TEXT,
  303. game_id TEXT,
  304. home BOOLEAN,
  305. league_id TEXT,
  306. score INTEGER,
  307. line_score TEXT,
  308. at_bats INTEGER,
  309. hits INTEGER,
  310. doubles INTEGER,
  311. triples INTEGER,
  312. homeruns INTEGER,
  313. rbi INTEGER,
  314. sacrifice_hits INTEGER,
  315. sacrifice_flies INTEGER,
  316. hit_by_pitch INTEGER,
  317. walks INTEGER,
  318. intentional_walks INTEGER,
  319. strikeouts INTEGER,
  320. stolen_bases INTEGER,
  321. caught_stealing INTEGER,
  322. grounded_into_double INTEGER,
  323. first_catcher_interference INTEGER,
  324. left_on_base INTEGER,
  325. pitchers_used INTEGER,
  326. individual_earned_runs INTEGER,
  327. team_earned_runs INTEGER,
  328. wild_pitches INTEGER,
  329. balks INTEGER,
  330. putouts INTEGER,
  331. assists INTEGER,
  332. errors INTEGER,
  333. passed_balls INTEGER,
  334. double_plays INTEGER,
  335. triple_plays INTEGER,
  336. PRIMARY KEY (team_id, game_id),
  337. FOREIGN KEY (team_id) REFERENCES team(team_id),
  338. FOREIGN KEY (game_id) REFERENCES game(game_id),
  339. FOREIGN KEY (team_id) REFERENCES team(team_id)
  340. );
  341. "
  342. dbExecute(conn, create_team_appearance_command)
  343. insert_to_team_appearance <- "
  344. INSERT OR IGNORE INTO team_appearance
  345. SELECT
  346. h_name,
  347. game_id,
  348. 1 AS home,
  349. h_league,
  350. h_score,
  351. h_line_score,
  352. h_at_bats,
  353. h_hits,
  354. h_doubles,
  355. h_triples,
  356. h_homeruns,
  357. h_rbi,
  358. h_sacrifice_hits,
  359. h_sacrifice_flies,
  360. h_hit_by_pitch,
  361. h_walks,
  362. h_intentional_walks,
  363. h_strikeouts,
  364. h_stolen_bases,
  365. h_caught_stealing,
  366. h_grounded_into_double,
  367. h_first_catcher_interference,
  368. h_left_on_base,
  369. h_pitchers_used,
  370. h_individual_earned_runs,
  371. h_team_earned_runs,
  372. h_wild_pitches,
  373. h_balks,
  374. h_putouts,
  375. h_assists,
  376. h_errors,
  377. h_passed_balls,
  378. h_double_plays,
  379. h_triple_plays
  380. FROM game_log
  381. UNION
  382. SELECT
  383. v_name,
  384. game_id,
  385. 0 AS home,
  386. v_league,
  387. v_score,
  388. v_line_score,
  389. v_at_bats,
  390. v_hits,
  391. v_doubles,
  392. v_triples,
  393. v_homeruns,
  394. v_rbi,
  395. v_sacrifice_hits,
  396. v_sacrifice_flies,
  397. v_hit_by_pitch,
  398. v_walks,
  399. v_intentional_walks,
  400. v_strikeouts,
  401. v_stolen_bases,
  402. v_caught_stealing,
  403. v_grounded_into_double,
  404. v_first_catcher_interference,
  405. v_left_on_base,
  406. v_pitchers_used,
  407. v_individual_earned_runs,
  408. v_team_earned_runs,
  409. v_wild_pitches,
  410. v_balks,
  411. v_putouts,
  412. v_assists,
  413. v_errors,
  414. v_passed_balls,
  415. v_double_plays,
  416. v_triple_plays
  417. from game_log;
  418. "
  419. dbExecute(conn, insert_to_team_appearance)
  420. check_query_8 <- "
  421. SELECT * FROM team_appearance
  422. WHERE game_id = (
  423. SELECT MIN(game_id) from game
  424. )
  425. OR game_id = (
  426. SELECT MAX(game_id) from game
  427. )
  428. ORDER By game_id, home;
  429. "
  430. check <- dbGetQuery(conn, check_query_8)
  431. head(check)
  432. ```
  433. # Adding the Person Appearance Table
  434. ```{r}
  435. drop_person_appearance_precaution <- "DROP TABLE IF EXISTS person_appearance"
  436. dbExecute(conn, drop_person_appearance_precaution)
  437. create_person_appearance_command <- "
  438. CREATE TABLE person_appearance (
  439. appearance_id INTEGER PRIMARY KEY,
  440. person_id TEXT,
  441. team_id TEXT,
  442. game_id TEXT,
  443. appearance_type_id,
  444. FOREIGN KEY (person_id) REFERENCES person(person_id),
  445. FOREIGN KEY (team_id) REFERENCES team(team_id),
  446. FOREIGN KEY (game_id) REFERENCES game(game_id),
  447. FOREIGN KEY (appearance_type_id) REFERENCES appearance_type(appearance_type_id)
  448. );
  449. "
  450. dbExecute(conn, create_person_appearance_command)
  451. insert_to_person_appearance <- '
  452. INSERT OR IGNORE INTO person_appearance (
  453. game_id,
  454. team_id,
  455. person_id,
  456. appearance_type_id
  457. )
  458. SELECT
  459. game_id,
  460. NULL,
  461. hp_umpire_id,
  462. "UHP"
  463. FROM game_log
  464. WHERE hp_umpire_id IS NOT NULL
  465. UNION
  466. SELECT
  467. game_id,
  468. NULL,
  469. [1b_umpire_id],
  470. "U1B"
  471. FROM game_log
  472. WHERE "1b_umpire_id" IS NOT NULL
  473. UNION
  474. SELECT
  475. game_id,
  476. NULL,
  477. [2b_umpire_id],
  478. "U2B"
  479. FROM game_log
  480. WHERE [2b_umpire_id] IS NOT NULL
  481. UNION
  482. SELECT
  483. game_id,
  484. NULL,
  485. [3b_umpire_id],
  486. "U3B"
  487. FROM game_log
  488. WHERE [3b_umpire_id] IS NOT NULL
  489. UNION
  490. SELECT
  491. game_id,
  492. NULL,
  493. lf_umpire_id,
  494. "ULF"
  495. FROM game_log
  496. WHERE lf_umpire_id IS NOT NULL
  497. UNION
  498. SELECT
  499. game_id,
  500. NULL,
  501. rf_umpire_id,
  502. "URF"
  503. FROM game_log
  504. WHERE rf_umpire_id IS NOT NULL
  505. UNION
  506. SELECT
  507. game_id,
  508. v_name,
  509. v_manager_id,
  510. "MM"
  511. FROM game_log
  512. WHERE v_manager_id IS NOT NULL
  513. UNION
  514. SELECT
  515. game_id,
  516. h_name,
  517. h_manager_id,
  518. "MM"
  519. FROM game_log
  520. WHERE h_manager_id IS NOT NULL
  521. UNION
  522. SELECT
  523. game_id,
  524. CASE
  525. WHEN h_score > v_score THEN h_name
  526. ELSE v_name
  527. END,
  528. winning_pitcher_id,
  529. "AWP"
  530. FROM game_log
  531. WHERE winning_pitcher_id IS NOT NULL
  532. UNION
  533. SELECT
  534. game_id,
  535. CASE
  536. WHEN h_score < v_score THEN h_name
  537. ELSE v_name
  538. END,
  539. losing_pitcher_id,
  540. "ALP"
  541. FROM game_log
  542. WHERE losing_pitcher_id IS NOT NULL
  543. UNION
  544. SELECT
  545. game_id,
  546. CASE
  547. WHEN h_score > v_score THEN h_name
  548. ELSE v_name
  549. END,
  550. saving_pitcher_id,
  551. "ASP"
  552. FROM game_log
  553. WHERE saving_pitcher_id IS NOT NULL
  554. UNION
  555. SELECT
  556. game_id,
  557. CASE
  558. WHEN h_score > v_score THEN h_name
  559. ELSE v_name
  560. END,
  561. winning_rbi_batter_id,
  562. "AWB"
  563. FROM game_log
  564. WHERE winning_rbi_batter_id IS NOT NULL
  565. UNION
  566. SELECT
  567. game_id,
  568. v_name,
  569. v_starting_pitcher_id,
  570. "PSP"
  571. FROM game_log
  572. WHERE v_starting_pitcher_id IS NOT NULL
  573. UNION
  574. SELECT
  575. game_id,
  576. h_name,
  577. h_starting_pitcher_id,
  578. "PSP"
  579. FROM game_log
  580. WHERE h_starting_pitcher_id IS NOT NULL;
  581. '
  582. dbExecute(conn, insert_to_person_appearance)
  583. ```
  584. ```{r}
  585. for (letter in c("h", "v")) {
  586. for (num in 1:9) {
  587. template <- '
  588. INSERT INTO person_appearance (
  589. game_id,
  590. team_id,
  591. person_id,
  592. appearance_type_id
  593. )
  594. SELECT
  595. game_id,
  596. %s_name,
  597. %s_player_%f_id,
  598. "O%f"
  599. FROM game_log
  600. WHERE %s_player_%f_id IS NOT NULL
  601. UNION
  602. SELECT
  603. game_id,
  604. %s_name,
  605. %s_player_%f_id,
  606. "D" || CAST(%s_player_%f_def_pos AS INT)
  607. FROM game_log
  608. WHERE %s_player_%f_id IS NOT NULL;
  609. '
  610. # replace all of the %s and %f with the correct letter number
  611. template <- gsub("%s", letter, template, fixed = TRUE)
  612. template <- gsub("%f", num, template, fixed = TRUE)
  613. dbExecute(conn, template)
  614. }
  615. }
  616. ```
  617. This particular solution incorporates a bit of regular expression and some nested for loops. If you need to review for-loops again, refer to our older mission on [control structures](https://www.dataquest.io/m/338-working-with-control-structures/). Regular expression is a technique where we look for specific patterns in a character vector and replace it with another pattern. In this case, we need to replace all the instances of "%s" and "%f" with a new letter and number, respectively. In particular, the `gsub()` function replaces *all* instances of "%s" and "%f" respectively. With each run of the nested loop, we get a properly formatted query that fulfills our needs. Using loops is one potential solution, but it's also possible to vectorize this work and recreate what we need.
  618. # Removing the Original Tables
  619. ```{r}
  620. # Check the current status of the db file
  621. dbListTables(conn)
  622. # Iterate through each of the tables
  623. tables <- c("game_log", "park_codes",
  624. "team_codes", "person_codes")
  625. for (t in tables) {
  626. drop_command = sprintf("DROP TABLE %s", t)
  627. dbExecute(conn, drop_command)
  628. }
  629. # Make sure that everything is gone
  630. dbListTables(conn)
  631. dbDisconnect(conn)
  632. ```