Home > OS >  How to create a data frame in R (without using nested for loops), which records estimations from oth
How to create a data frame in R (without using nested for loops), which records estimations from oth

Time:07-14

I want to store the distances between each point (x,y) of two 2D trajectories. So I have 4 vectors: ax, ay that has time dependent coordinates of particle a and bx, by for particle b. I want to create a data frame dist that will basically be:

dist[t1,t2] = sqrt((ax[t1]-bx[t1])**2 (ay[t1]-by[t2])**2)

Now I want to do this without using nested for loops with t1 and t2, as it will take a lot of time for tmax~1000. Is there any cool dataframe trick or any of the apply methods to achieve this?

CodePudding user response:

First, let's make the data reproducible. You should do that yourself in your next questions.

ax <- 1:3
ay <- 4:6
bx <- 3:1
by <- 6:4

R being vectorized, you don't need to include indexes in your statement.

dist <- sqrt((ax-bx)^2 (ay-by)^2)
result <- data.frame(ax, ay, bx, by, dist)
> result
  ax ay bx by     dist
1  1  4  3  6 2.828427
2  2  5  2  5 0.000000
3  3  6  1  4 2.828427

CodePudding user response:

The outer function is useful for this, you could do:

outer(seq_along(ax), seq_along(bx), 
function(t1,t2){sqrt((ax[t1]-bx[t2])**2 (ay[t1]-by[t2])**2)})

I've made a slight change to your calculation: bx[t1] became bx[t2], which I think is correct

  • Related