Skip to content
Prev 370011 / 398503 Next

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

Hello,

The obvious way would be to preallocate the resulting data.frame, to 
expand an empty one on each iteration being a time expensive operation.

n <- nrow(expand.grid(1:nrow(D1), 1:nrow(D2)))
D4 <- data.frame(distance=integer(n),difference=integer(n))
k <- 0
for (i in 1:nrow(D1)){
	for (j in 1:nrow(D2))  {
		k <- k + 1
		D4[k, ] <- 
c(distance=sqrt(sum((D1[i,1:2]-D2[j,1:2])^2)),difference=(D1[i,3]-D2[j,3])^2)
	}
}

identical(D3, D4)

Hope this helps,

Rui Barradas

Em 23-06-2017 16:19, Rathore, Saubhagya Singh escreveu: