beanumber / baseball_R

Companion to Analyzing Baseball Data with R, 2nd edition
95 stars 62 forks source link

Chapter 3: Graph of the 1998 home run race #10

Closed Grav8808 closed 3 years ago

Grav8808 commented 3 years ago

Hey man,

I am working through the lessons and homework and I am having trouble running the graph in section 3.8.3. I keep getting the following error.

ggplot(hr_ytd, aes(Date, cumHR, linetype = nameLast)) + geom_line() + geom_hline(yintercept = 62, color = crcblue) + annotate("text", ymd("1998-04-15"), 65, label = "62", color = crcblue) + ylab("Home Runs in the Season")

Error in xj[i] : object of type 'closure' is not subsettable

I believe it has something to do with R not being able to subset a function. I am thinking the error is being caused by this line of code.

library(lubridate) cum_hr <- function(d) { d %>% mutate(Date = ymd(str_sub(GAME_ID, 4, 11))) %>% arrange(Date) %>% mutate(HR = ifelse(EVENT_CD == 23, 1, 0), cumHR = cumsum(HR)) %>% select(Date, cumHR) }

I am brand new to R so if I am making an obvious mistake I apologize in advance :D

beanumber commented 3 years ago

Hi @Grav8808 , do you have crcblue defined? Try running crcblue <- "blue" first, and then try this code again.

The problem is that something that you think is a subsettable object (most likely a data.frame) is actually a function. Usually this happens when you forget to define your data, and there is a function with the same name in a package that you have loaded.

You might find this helpful:

https://rstudio.com/resources/rstudioconf-2020/object-of-type-closure-is-not-subsettable/

Grav8808 commented 3 years ago

Worked perfect, Thank you!