0

I am currently working on a project for which I am interested in calculating the distance between the location of a basketball player and the ball during an event. To do this I created the following function:

## Euclidean distance
distance <- function(x,y){
  x2 <- (x[i]-x[j])^2
  y2 <- (y[i]-y[j])^2
  dis <- sqrt(x2+y2)
}

What I want to achieve is to calculate the distance between the basketball and the players, and then repeat this process for each time frame of data I have. So for each time frame x1 and y1 would have to be constant whilst x[j] and y[j] would keep going from 2 to 11. I thought of this nested for loop, but it is giving me a constant result of 28.34639. I added a link to an image of a sample of my data frame. Data Frame Sample

for(i in i:length(all.movement$x_loc)){
  for(j in j:11){
    all.movement$distance[j] <- distance(all.movement$x_loc, all.movement$y_loc)
    }
  i <- i + 11
}

I would really appreciate some help with this problem.

Bmaik
  • 43
  • 1
  • 4
  • 2
    Possible duplicate of [Calculating all distances between one point and a group of points efficiently in R](http://stackoverflow.com/questions/3029639/calculating-all-distances-between-one-point-and-a-group-of-points-efficiently-in) – ArunK May 26 '16 at 09:23
  • 1
    You may want to take a look at `?dist` – RHertel May 26 '16 at 09:41

1 Answers1

0

I'd go about:

set.seed(101)
x <- rnorm(30, 10, 5) # x coordinate
y <- rnorm(30, 15, 7) # y coordinate
df <- data.frame(x, y) # sample data.frame
i = 0
for (i in i:length(df$x)) {
df$distance <- sqrt((x - 5)^2 + (y + 4)^2)} # assume basket coordinates (5, -4)
df # output