Install and load necessary packages

options(repos = c(CRAN = "https://cran.rstudio.com"))
req_packages <- c("DBI","RMySQL","dplyr","dbplyr","knitr","tidyr", "readr", "stringr","tibble", "rmarkdown", "purrr", "lubridate", "here", "httr2", "RCurl")
for (pkg in req_packages) {
  if (!require(pkg, character.only = TRUE)) {
    message(paste("Installing package:", pkg))
    install.packages(pkg, dependencies = TRUE)
  } else {
    message(paste(pkg, " already installed."))
  }
  library(pkg, character.only = TRUE)
}
## Loading required package: DBI
## DBI  already installed.
## Loading required package: RMySQL
## RMySQL  already installed.
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## dplyr  already installed.
## Loading required package: dbplyr
## 
## Attaching package: 'dbplyr'
## The following objects are masked from 'package:dplyr':
## 
##     ident, sql
## dbplyr  already installed.
## Loading required package: knitr
## knitr  already installed.
## Loading required package: tidyr
## tidyr  already installed.
## Loading required package: readr
## readr  already installed.
## Loading required package: stringr
## stringr  already installed.
## Loading required package: tibble
## tibble  already installed.
## Loading required package: rmarkdown
## rmarkdown  already installed.
## Loading required package: purrr
## purrr  already installed.
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## lubridate  already installed.
## Loading required package: here
## here() starts at /Users/paulabrown/Documents/CUNY SPS- Data 607/Project1
## here  already installed.
## Loading required package: httr2
## httr2  already installed.
## Loading required package: RCurl
## 
## Attaching package: 'RCurl'
## The following object is masked from 'package:tidyr':
## 
##     complete
## RCurl  already installed.

Check if file exists

Read the file

This step will check if the raw data from the “tournamentinfo.txt” file exists in my GitHub repository and then reads the lines in the file if it does exist. Otherwise, a message “File not found at the specified GitHub URL” is displayed.

url <- "https://raw.githubusercontent.com/PaulaB989/data/main/tournamentinfo.txt"
if (RCurl::url.exists(url)) {
  file_lines <- readLines(url)
} else {
  stop("File not found at the specified GitHub URL.")
}
## Warning in readLines(url): incomplete final line found on
## 'https://raw.githubusercontent.com/PaulaB989/data/main/tournamentinfo.txt'

Begin formatting the .txt data using regular expressions (regex) - identifying a pattern and returning the strings.

This is one example of regex use in this project (“^\s*\d+\s\|“)

#Grab lines that start with a player number and contains chess match data.
# ^ = start of line
# \\s* = optional whitespace
# \\d+ = 1 or more digits (player number)
# \\s\\| = space followed by a pipe ("|")
player_lines <- file_lines[str_detect(file_lines, "^\\s*\\d+\\s\\|")]

# Grab lines that start with a state abbreviation and contains player info like pre-rating
# ^ = start of line
# \\s* = optional whitespace
# [A-Z]{2} = 2 capital letters (State abbreviation, i.e. OH, NY, etc...)
# \\s\\| = space followed by a pipe ("|")
state_lines  <- file_lines[str_detect(file_lines, "^\\s*[A-Z]{2}\\s\\|")]

Get Player-Info

chessplayer_df <- tibble(
  name = str_trim(str_sub(player_lines, 8, 38)),
  points = as.numeric(str_trim(str_sub(player_lines, 42, 44))),
  opponents = str_extract_all(player_lines, "\\d{1,2}(?=\\|)")
  # "\\d{1,2}(?=\\|)" = one or two digits followed by pipe character ("|") using a 'lookahead'("(?=\\|)") - what comes after current position.
)

Get Player-State and Pre-Rating-Info

playerstaterating_df <- tibble(
  state = str_trim(str_sub(state_lines, 4, 5)),
  pre_rating = as.numeric(str_extract(state_lines, "(?<=R: )\\s?\\d+"))
  # "(?<=R: )" = a positive lookbehind (what came before current position). It matches a position in the string that is preceded by the exact text "R: " — but it doesn't include "R: " in the match result.
  # "\\s?" = optional space ** The 3 digit pre-ratings has an additional space after "R: " without using "\\s?" the pre-rating values for those lines returns "NA".
  # "\\d+" = matches one or more digits (0–9). The double backslash is used in R to escape the backslash in strings.
)

Combine/Bind Player and State data frames

chessplayer_df <- bind_cols(chessplayer_df, playerstaterating_df)

Calculate Opponent Ratings

# Build lookup table of player number to pre-rating
player_numbers <- str_extract(player_lines, "^\\s*\\d+")
rating_lookup <- tibble(
  number = as.integer(player_numbers),
  rating = playerstaterating_df$pre_rating
)

Calculate average opponent rating

chessplayer_df <- chessplayer_df %>%
  mutate(
    opponent_nums = str_extract_all(player_lines, "\\d{1,2}(?=\\|)"),
    opponent_ratings = lapply(opponent_nums, function(nums) {
      nums <- as.integer(nums)
      mean(rating_lookup$rating[match(nums, rating_lookup$number)], na.rm = TRUE)
    }),
    avg_opponent_rating = round(unlist(opponent_ratings), 0)
  ) %>%
  select(name, state, points, pre_rating, avg_opponent_rating)

Write to CSV

write_csv(chessplayer_df, here::here("tournament_results.csv"))
# "here::here" = helps you build file paths that are robust and reproducible, especially in R projects.

##Summarize the data in the .csv file

knitr::kable(chessplayer_df)
name state points pre_rating avg_opponent_rating
GARY HUA ON 6.0 1794 1605
DAKSHESH DARURI MI 6.0 1553 1469
ADITYA BAJAJ MI 6.0 1384 1564
PATRICK H SCHILLING MI 5.5 1716 1574
HANSHI ZUO MI 5.5 1655 1501
HANSEN SONG OH 5.0 1686 1519
GARY DEE SWATHELL MI 5.0 1649 1372
EZEKIEL HOUGHTON MI 5.0 1641 1468
STEFANO LEE ON 5.0 1411 1523
ANVIT RAO MI 5.0 1365 1554
CAMERON WILLIAM MC LEMAN MI 4.5 1712 1468
KENNETH J TACK MI 4.5 1663 1506
TORRANCE HENRY JR MI 4.5 1666 1498
BRADLEY SHAW MI 4.5 1610 1515
ZACHARY JAMES HOUGHTON MI 4.5 1220 1484
MIKE NIKITIN MI 4.0 1604 1386
RONALD GRZEGORCZYK MI 4.0 1629 1499
DAVID SUNDEEN MI 4.0 1600 1480
DIPANKAR ROY MI 4.0 1564 1426
JASON ZHENG MI 4.0 1595 1411
DINH DANG BUI ON 4.0 1563 1470
EUGENE L MCCLURE MI 4.0 1555 1300
ALAN BUI ON 4.0 1363 1214
MICHAEL R ALDRICH MI 4.0 1229 1357
LOREN SCHWIEBERT MI 3.5 1745 1363
MAX ZHU ON 3.5 1579 1507
GAURAV GIDWANI MI 3.5 1552 1222
SOFIA ADINA STANESCU-BELLU MI 3.5 1507 1522
CHIEDOZIE OKORIE MI 3.5 1602 1314
GEORGE AVERY JONES ON 3.5 1522 1144
RISHI SHETTY MI 3.5 1494 1260
JOSHUA PHILIP MATHEWS ON 3.5 1441 1379
JADE GE MI 3.5 1449 1277
MICHAEL JEFFERY THOMAS MI 3.5 1399 1375
JOSHUA DAVID LEE MI 3.5 1438 1150
SIDDHARTH JHA MI 3.5 1355 1388
AMIYATOSH PWNANANDAM MI 3.5 980 1385
BRIAN LIU MI 3.0 1423 1539
JOEL R HENDON MI 3.0 1436 1430
FOREST ZHANG MI 3.0 1348 1391
KYLE WILLIAM MURPHY MI 3.0 1403 1248
JARED GE MI 3.0 1332 1150
ROBERT GLEN VASEY MI 3.0 1283 1107
JUSTIN D SCHILLING MI 3.0 1199 1327
DEREK YAN MI 3.0 1242 1152
JACOB ALEXANDER LAVALLEY MI 3.0 377 1358
ERIC WRIGHT MI 2.5 1362 1392
DANIEL KHAIN MI 2.5 1382 1356
MICHAEL J MARTIN MI 2.5 1291 1286
SHIVAM JHA MI 2.5 1056 1296
TEJAS AYYAGARI MI 2.5 1011 1356
ETHAN GUO MI 2.5 935 1495
JOSE C YBARRA MI 2.0 1393 1345
LARRY HODGE MI 2.0 1270 1206
ALEX KONG MI 2.0 1186 1406
MARISA RICCI MI 2.0 1153 1414
MICHAEL LU MI 2.0 1092 1363
VIRAJ MOHILE MI 2.0 917 1391
SEAN M MC CORMICK MI 2.0 853 1319
JULIA SHEN MI 1.5 967 1330
JEZZEL FARKAS ON 1.5 955 1327
ASHWIN BALAJI MI 1.0 1530 1186
THOMAS JOSEPH HOSMER MI 1.0 1175 1350
BEN LI MI 1.0 1163 1263
# kable() = creates a nicely formatted table from a data frame or tibble.

Read the .csv file

chessplayer_df <- read_csv("/Users/paulabrown/Documents/CUNY SPS- Data 607/Project1/tournament_results.csv")
## Rows: 64 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): name, state
## dbl (3): points, pre_rating, avg_opponent_rating
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Connect to DB

  1. Create the “Chess_Tournament” database if it does not exist.
  2. Safely Disconnect.
 readRenviron("~/Documents/CUNY SPS- Data 607/Week 2A Assignment/.Renviron")
databaseconnect <- dbConnect(
  RMySQL::MySQL(),
  host     = Sys.getenv("DB3_HOST"),     
  port     = as.integer(Sys.getenv("DB3_PORT")),                  
  user     = Sys.getenv("DB3_USER"),
  password = Sys.getenv("DB3_PASSWORD")
)
dbExecute(databaseconnect, "CREATE DATABASE IF NOT EXISTS Chess_Tournament")
## [1] 1
dbDisconnect(databaseconnect)
## [1] TRUE

Connect to the new database

readRenviron("~/Documents/CUNY SPS- Data 607/Week 2A Assignment/.Renviron")
newDB <- dbConnect(
  RMySQL::MySQL(),
  dbname   = Sys.getenv("DB3_NAME"),
  host     = Sys.getenv("DB3_HOST"),     
  port     = as.integer(Sys.getenv("DB3_PORT")),                  
  user     = Sys.getenv("DB3_USER"),
  password = Sys.getenv("DB3_PASSWORD"),
  client.flag = CLIENT_LOCAL_FILES
)

Import the .csv data into new database table

dbWriteTable(newDB, "tournament_results", chessplayer_df, row.names = FALSE, overwrite = TRUE)
## [1] TRUE

Check database table exists

dbListTables(newDB)
## [1] "tournament_results"

View the data in the database table

dbGetQuery(newDB, "SELECT * FROM tournament_results")
##                          name state points pre_rating avg_opponent_rating
## 1                    GARY HUA    ON    6.0       1794                1605
## 2             DAKSHESH DARURI    MI    6.0       1553                1469
## 3                ADITYA BAJAJ    MI    6.0       1384                1564
## 4         PATRICK H SCHILLING    MI    5.5       1716                1574
## 5                  HANSHI ZUO    MI    5.5       1655                1501
## 6                 HANSEN SONG    OH    5.0       1686                1519
## 7           GARY DEE SWATHELL    MI    5.0       1649                1372
## 8            EZEKIEL HOUGHTON    MI    5.0       1641                1468
## 9                 STEFANO LEE    ON    5.0       1411                1523
## 10                  ANVIT RAO    MI    5.0       1365                1554
## 11   CAMERON WILLIAM MC LEMAN    MI    4.5       1712                1468
## 12             KENNETH J TACK    MI    4.5       1663                1506
## 13          TORRANCE HENRY JR    MI    4.5       1666                1498
## 14               BRADLEY SHAW    MI    4.5       1610                1515
## 15     ZACHARY JAMES HOUGHTON    MI    4.5       1220                1484
## 16               MIKE NIKITIN    MI    4.0       1604                1386
## 17         RONALD GRZEGORCZYK    MI    4.0       1629                1499
## 18              DAVID SUNDEEN    MI    4.0       1600                1480
## 19               DIPANKAR ROY    MI    4.0       1564                1426
## 20                JASON ZHENG    MI    4.0       1595                1411
## 21              DINH DANG BUI    ON    4.0       1563                1470
## 22           EUGENE L MCCLURE    MI    4.0       1555                1300
## 23                   ALAN BUI    ON    4.0       1363                1214
## 24          MICHAEL R ALDRICH    MI    4.0       1229                1357
## 25           LOREN SCHWIEBERT    MI    3.5       1745                1363
## 26                    MAX ZHU    ON    3.5       1579                1507
## 27             GAURAV GIDWANI    MI    3.5       1552                1222
## 28 SOFIA ADINA STANESCU-BELLU    MI    3.5       1507                1522
## 29           CHIEDOZIE OKORIE    MI    3.5       1602                1314
## 30         GEORGE AVERY JONES    ON    3.5       1522                1144
## 31               RISHI SHETTY    MI    3.5       1494                1260
## 32      JOSHUA PHILIP MATHEWS    ON    3.5       1441                1379
## 33                    JADE GE    MI    3.5       1449                1277
## 34     MICHAEL JEFFERY THOMAS    MI    3.5       1399                1375
## 35           JOSHUA DAVID LEE    MI    3.5       1438                1150
## 36              SIDDHARTH JHA    MI    3.5       1355                1388
## 37       AMIYATOSH PWNANANDAM    MI    3.5        980                1385
## 38                  BRIAN LIU    MI    3.0       1423                1539
## 39              JOEL R HENDON    MI    3.0       1436                1430
## 40               FOREST ZHANG    MI    3.0       1348                1391
## 41        KYLE WILLIAM MURPHY    MI    3.0       1403                1248
## 42                   JARED GE    MI    3.0       1332                1150
## 43          ROBERT GLEN VASEY    MI    3.0       1283                1107
## 44         JUSTIN D SCHILLING    MI    3.0       1199                1327
## 45                  DEREK YAN    MI    3.0       1242                1152
## 46   JACOB ALEXANDER LAVALLEY    MI    3.0        377                1358
## 47                ERIC WRIGHT    MI    2.5       1362                1392
## 48               DANIEL KHAIN    MI    2.5       1382                1356
## 49           MICHAEL J MARTIN    MI    2.5       1291                1286
## 50                 SHIVAM JHA    MI    2.5       1056                1296
## 51             TEJAS AYYAGARI    MI    2.5       1011                1356
## 52                  ETHAN GUO    MI    2.5        935                1495
## 53              JOSE C YBARRA    MI    2.0       1393                1345
## 54                LARRY HODGE    MI    2.0       1270                1206
## 55                  ALEX KONG    MI    2.0       1186                1406
## 56               MARISA RICCI    MI    2.0       1153                1414
## 57                 MICHAEL LU    MI    2.0       1092                1363
## 58               VIRAJ MOHILE    MI    2.0        917                1391
## 59          SEAN M MC CORMICK    MI    2.0        853                1319
## 60                 JULIA SHEN    MI    1.5        967                1330
## 61              JEZZEL FARKAS    ON    1.5        955                1327
## 62              ASHWIN BALAJI    MI    1.0       1530                1186
## 63       THOMAS JOSEPH HOSMER    MI    1.0       1175                1350
## 64                     BEN LI    MI    1.0       1163                1263