I'm trying to calculate Slugging Percentage from baseball in a Data Frame in R called "batting", created from the "Batting.csv" found on Sean Lahaman's Website.
The formula for Slugging Percentage per Wikipedia is as follows: ([Singles] + [Doubles x 2] + [Triples x 3] + [Home Runs x 4])/[At Bats]
(Which is essentially total bases divided by at bats).
Here is my R code:
# Import batting data
batting <- read.csv('Batting.csv')
# Create X1B (Singles)
batting$X1B <- batting$H - batting$X2B - batting$X3B - batting$HR
# Create Slugging Average (SLG)
batting$SLG <-
((1 * batting$x1B) + (2 * batting$X2B) + (3 * batting$X3B) + (4 * batting$HR)) /
batting$AB
Here is the error message:
Error in `$<-.data.frame`(`*tmp*`, SLG, value = numeric(0)) :
replacement has 0 rows, data has 97889