# R function error `replacement has length zero` trouble?

I am defining the following function to identify the nearest other individuals within the same group (both their distance and their id):

``````get_min_opp_dist <- function(position_table) {

min_dist <- vector(mode = "double", length = nrow(position_table))
min_dist_idx <- vector(mode = "logical", length = nrow(position_table))

for (i in 1:nrow(position_table)) {
x <- position_table\$x[i]
y <- position_table\$y[i]
team <- position_table\$team[i]

if (team == "ball") {
next()
}

idx <- position_table\$team != team & position_table\$team != "ball"
min_dist[i] = min(sqrt((x - position_table\$x[idx])^2 + (y - position_table\$y[idx])^2))

Id_sub <- position_table\$Id[idx]

min_dist_idx[i] <- Id_sub[which.min(sqrt((x - position_table\$x[idx])^2 + (y - position_table\$y[idx])^2))]

}

position_table\$opp_min_dist <- min_dist
position_table\$opp_min_dist_idx <- min_dist_idx

return(position_table)

}
``````

I then run the function using:

``````data <- data %>%
group_by(var1, var2, var3, var4)
data <- group_split(data)
data <- lapply(data, get_min_opp_dist)
data <- bind_rows(data)
``````

However, this throws the following error when running lapply:

``````Error in min_dist_x[i] <- x_sub[which.min(sqrt((x - position_table\$x[idx])^2 +  :
replacement has length zero
Called from: FUN(X[[i]], ...)
``````

I have tried debugging this, but haven't had any luck. This function works with a small chunk of data, but when I apply it to my entire data, it breaks. Because the dataset is so large (far too large to provide for MRE), it takes 20 minutes just to get to the debugger. I'm out of ideas. What does the error even mean and how can I fix it?