# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R
#     language: R
#     name: ir
# ---

# +
#https://vincentarelbundock.github.io/Rdatasets/datasets.html
#Yearly batting records for all major league baseball players 
#read in the CSV file as available on the site

players <- read.csv(file="Documents/baseball.csv", header=TRUE, sep=",")
head(players)
# -

library(dplyr)

playerst <- tbl_df(players)
playerst

glimpse(playerst)

data <- sample_n(players, 30)
glimpse(data)

#filter only players with over 200 hits in a season
over200 <- filter(players, h > 200)
head(over200)
nrow(over200)

over200and40hr <- filter(players, h > 200 & hr > 40)
head(over200and40hr)
nrow(over200and40hr)

filter(players, h > 300)

# add column percentage of times at bat player got a hit
pct <- mutate(players, hitpct = h / ab)
head(pct)
summary(pct)

summarise(pct, mean(hitpct, na.rm = TRUE))

library(magrittr)
pct %>% summarise(hitpct %>% mean(na.rm = TRUE))

quantile(pct$hitpct, probs = 0.99, na.rm = TRUE)

top_players <- filter(pct, hitpct > 0.47)
top_players <- top_players[order(top_players$hitpct) , ]
head(top_players)
nrow(top_players)

#new
top_players %>% filter(id == "ruthba01")

# +
#new TODO
#starwars %>%
#  group_by(species) %>%
#  summarise(
#    n = n(),
#    mass = mean(mass, na.rm = TRUE)
#  ) %>%
#  filter(n > 1)
# -

teamhitpct <- summarise(group_by(pct, team), mean(hitpct, na.rm = TRUE))
names(teamhitpct) <- c("team", "hitpct")
summary(teamhitpct)

teamhitpct <- teamhitpct[order(-teamhitpct$hitpct) , ]
head(teamhitpct)

quantile(teamhitpct$hitpct, probs = 0.99)

#new
by_team <- group_by(players, team)
by_team

#new
summarize(by_team,mean(h / ab))

StarcoderdataJupyterScriptsDedupFiltered