multmerge = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.csv(file=x,header=T)})
Reduce(function(x,y) {merge(x,y,all = TRUE)}, datalist)
}
season <- multmerge("/Users/maxbrown/DukeBase/2023 Season Data")
season_FL <- season %>% filter(PitchCall == "InPlay" & Distance > 150 &
PlayResult != "HomeRun" & (TaggedHitType == "LineDrive" | TaggedHitType == "FlyBall"
| TaggedHitType == "Popup"))
season_FL <- season_FL %>% mutate(fielder = case_when(
Bearing < -15 ~ "Left",
Bearing > -15 & Bearing < 15 ~ "Center",
Bearing > 15 ~ "Right"
))
plot <- plot_ly(type = "scatter", mode = "markers")
plot <- add_trace(plot, x = season_FL$Bearing,
y = season_FL$Distance, color = season_FL$fielder,
mode = "markers", marker = list(size = ~season_FL$HangTime))
plot
left <- season_FL %>% filter(fielder == "Left")
center <- season_FL %>% filter(fielder == "Center")
right <- season_FL %>% filter(fielder == "Right")
# Function to calculate total distance for a given point
calculate_total_distance <- function(point, df) {
distances <- sqrt((df$Bearing - point[1])^2 + (df$Distance - point[2])^2)
total_distance <- sum(distances)
return(total_distance)
}
# Use optimization functions to find the point that minimizes total distance
optimized_point <- optim(
c(0, 0), # Initial guess for x and y
calculate_total_distance, # Objective function
df = left, # Additional parameters to pass to the objective function
method = "L-BFGS-B" # Optimization method
)$par
# Print the result
print("Optimized Point for Left Fielder:")
## [1] "Optimized Point for Left Fielder:"
print(optimized_point)
## [1] -27.5558 270.6393
# Use optimization functions to find the point that minimizes total distance
optimized_point <- optim(
c(0, 0), # Initial guess for x and y
calculate_total_distance, # Objective function
df = center, # Additional parameters to pass to the objective function
method = "L-BFGS-B" # Optimization method
)$par
# Print the result
print("Optimized Point for Center Fielder:")
## [1] "Optimized Point for Center Fielder:"
print(optimized_point)
## [1] 0.4128982 297.6287697
# Use optimization functions to find the point that minimizes total distance
optimized_point <- optim(
c(0, 0), # Initial guess for x and y
calculate_total_distance, # Objective function
df = right, # Additional parameters to pass to the objective function
method = "L-BFGS-B" # Optimization method
)$par
# Print the result
print("Optimized Point for Right Fielder:")
## [1] "Optimized Point for Right Fielder:"
print(optimized_point)
## [1] 29.27219 274.20652