1

I am trying to look at the baseball data from 1903 through 1960 from the Lahman database. I am doing this for my own research. I am wanting to use the batting table, which does not include batting average, slugging, OBP or OPS.

I want to calculate those, but I first need to get total bases. I am having trouble getting the program to calculate total bases with the X2B and X3B.

I've looked into trying as.numeric, but I couldn't get it to work. This is using R and R studio. I've tried putting quotes around X2B and X3B for the doubles and triples and without quotes.

batting_1960 <- batting_1903 %>%  
  filter(yearID <= 1960 & G >= 90) %>% 
  mutate(Batting_Average = H/AB, TB = (2*"X2B")+(3*"X3B")+HR+(H-"X2B"-"X3B"-HR)) %>% 
  arrange(yearID, desc(Batting_Average))

I expect that for each row of data, that the total bases will be calculated in a new column but I get the error:

Error in 2 * "X2B" : non-numeric argument to binary operator 

This would be so that I could eventually calculated OPS, OBP and slugging.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
R white
  • 21
  • 1
  • 1
    Please include sample data related to your problem. – Tim Biegeleisen May 19 '19 at 01:20
  • Welcome to Stack Overflow! In the future, it is helpful to reduce your example down to the simplest form possible. It helps others reproduce your problem, and makes it easier (and more likely) for people to help you. See: https://stackoverflow.com/q/5963269, also [mcve] – John Colby May 19 '19 at 05:55

1 Answers1

0

Your code is trying to mutiply 2 by the literal string "X2B", which is not going to work. Column names should be unquoted in mutate().

Your error:

> tibble(X2B = 1:10) %>% mutate(TB = 2 * "X2B")
Error in 2 * "X2B" : non-numeric argument to binary operator

Should be, for example:

> tibble(X2B = 1:10) %>% mutate(TB = 2 * X2B)
# A tibble: 10 x 2
     X2B    TB
   <int> <dbl>
 1     1     2
 2     2     4
 3     3     6
 4     4     8
 5     5    10
 6     6    12
 7     7    14
 8     8    16
 9     9    18
10    10    20
John Colby
  • 22,169
  • 4
  • 57
  • 69