Search code examples
rdataframeapplynested-for-loop

How to create a data frame in R (without using nested for loops), which records estimations from other vectors?


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[t2])**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?


Solution

  • 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