[R] R version 3.3.2, Windows 10: Applying a function to each possible pair of rows from two different data-frames

Rathore, Saubhagya Singh
Fri, 23 Jun 2017 15:19:08 -0000

For certain reason, the content was not visible in the last mail, so posting it
again.

Dear Members,

I have two different dataframes with a different number of rows. I need to apply
a set of functions to each possible combination of rows with one row coming from
1st dataframe and other from 2nd dataframe. Though I am able to perform this
task using for loops, I feel that there must be a more efficient way to do it.
An example case is given below. D1 and D2 are two dataframes. I need to evaluate
D3 with one column as the Euclidean distance in the x-y plane and second column
as squared difference of z values, of each row pair from D1 and D2.

D1<-data.frame(x=1:5,y=6:10,z=rnorm(5))
D2<-data.frame(x=19:30,y=41:52,z=rnorm(12))
D3<-data.frame(distance=integer(0),difference=integer(0))

for (i in 1:nrow(D1)){

for (j in 1:nrow(D2))  {

temp<-data.frame(distance=sqrt(sum((D1[i,1:2]-D2[j,1:2])^2)),difference=(D1[i,3]-D2[j,3])^2)
D3<-rbind(D3,temp)
}
}

Thank you

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of r-help-owner
at r-project.org
Sent: Friday, June 23, 2017 10:47 AM
To: Rathore, Saubhagya Singh <saubhagya at gatech.edu>
Subject: R version 3.3.2, Windows 10: Applying a function to each possible pair
of rows from two different data-frames

The message's content type was not explicitly allowed