This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Cmd+Shift+Enter.
getwd()
[1] "/Users/victorcuerdo/Library/CloudStorage/GoogleDrive-victormcuerdo@gmail.com/My Drive/MDC/Special Topics - Sport Analytics/In class activity # 7"
baseball = read.csv("baseball.csv")
# Subset to only include moneyball years (before 2002)
moneyball = subset(baseball, Year < 2002)
# Compute Run Difference
moneyball$RD = moneyball$RS - moneyball$RA
# Regression model to predict wins from run difference
WinsReg = lm(W ~ RD, data = moneyball)
summary(WinsReg)
Call:
lm(formula = W ~ RD, data = moneyball)
Residuals:
Min 1Q Median 3Q Max
-14.2662 -2.6509 0.1234 2.9364 11.6570
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 80.881375 0.131157 616.67 <2e-16 ***
RD 0.105766 0.001297 81.55 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 3.939 on 900 degrees of freedom
Multiple R-squared: 0.8808, Adjusted R-squared: 0.8807
F-statistic: 6651 on 1 and 900 DF, p-value: < 2.2e-16
# Predict wins for a team that scores 763 and allows 614 runs
newteam = data.frame(RD = 763 - 614) # RD = 149
predict(WinsReg, newteam)
1
96.64045
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Cmd+Option+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Cmd+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.