-1

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
M--
  • 25,431
  • 8
  • 61
  • 93
Sescopeland
  • 315
  • 2
  • 16
  • Please read [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – M-- Jun 26 '17 at 19:36
  • There are no variables called `X2B` or `X3B`. – M-- Jun 26 '17 at 19:42
  • you have a typo: `1 * batting$x1B` should be `1 * batting$X1B` with capital `X`. Also, when I downloaded the data it was `batting$`2B`` instead of `batting$X2B`. Make sure variable names are correct and consistent. – M-- Jun 26 '17 at 19:49
  • `X1B` or `x1B`,upper case ? – BENY Jun 26 '17 at 19:56

1 Answers1

0

This works:

> batting$SLG = (batting$X1B + 2*batting$X2B + 3*batting$X3B + 4*batting$HR)/batting$AB
> summary(batting$SLG)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
  0.000   0.176   0.309   0.290   0.398   4.000   15381 

You have a lower-case x in batting$x1B in your example. Make sure it's capitalized as above.

Matt
  • 954
  • 1
  • 9
  • 24