i have following problem, I want to merge distance matrices, consider following data:
x1 <- c(2,2,2,3,1,2,4,6,1,2,4)
y1 <- c(5,4,3,3,4,2,1,6,4,2,3)
x2 <- c(8,2,7,3,1,2,2,2,1,2,6)
y2 <- c(1,3,3,3,1,2,4,3,1,2,8)
x3 <- c(4,4,1,2,4,6,3,2,4,6,9)
y3 <- c(1,2,3,3,1,2,4,6,1,2,1)
x4 <- c(4,4,1,2,4,6,3,2,4,6,9)
y4 <- c(1,2,3,3,1,2,4,6,1,2,1)
x5 <- c(4,1,2,4,6,2,3,3,6,2,9)
y5 <- c(1,3,3,3,1,2,4,6,1,2,1)
id1 <- c("a","a","a","a","b","b","b","b","b","b","b")
dat <- data.frame(x1,y1,x2,y2,x3,y3,id1)
I want to create the distances between the points in each group:
distance <- by(dat, list(id1=dat$id1), function(x){
dist(x, upper=TRUE, diag = TRUE)
})
How can I merge them (rbind, with NAs because the a matrix has less columns then) so that I can add the distances to the original dataset as new variables?
The final output should look like this
id1 Dist1 Dist2 Dist3 Dist4 Dist5 Dist6
a 0 7 5.066228 7 NA and so on ---
a 7 0 6.480741 3.05505 NA
a 5.066228 6.480741 0 4.582576 NA
a 7 3.05505 4.582576 0 NA
b 0 3.741657 6.658328 8.573214 0
b 3.741657 0 5.066228 8.708234 3.741657
b 6.658328 5.066228 0 6.390097 6.658328
b 8.573214 8.708234 6.390097 0 8.573214
b 0 3.741657 6.658328 8.573214 0
b 3.741657 0 5.066228 8.708234 3.741657
b 11.27682 8.841191 9.721111 12.220202 11.27682
Please note that in reality there are about 20 groups with in sum about 10000 lines of data. this is just a simplified version. Thanks!!
rbind? why notcbind? - David Arenburg