StevenL - 1 year ago 96
R Question

# connecting dots in 2 different data sets in R

I have 2 data sets (DSA and DSB) that contain x & y coordinates

``````tumor<- data.frame(DSA[,c("X_Parameter","Y_Parameter")])
cells<-data.frame(DSB[,c ("X_Parameter","Y_Parameter")])
plot(cells, xlim=c(1,1300), ylim=c(1,1000), col="red")
par(new=TRUE)
plot(tumor, xlim=c(1,1300), ylim=c(1,1000), col="blue")
``````

the plots make this graph

I want to be able to draw a connecting line from every red dot to every blue dot.
Does anyone know if this can be done. thanks

Sample
DSA=(5,5 6,6 5,6 6,5) DSB=(1,1 10,10 10,1 1,10)
what the plot should look like

Brute-force, perhaps inelegant:

``````DSA <- data.frame(x = c(5, 6, 5, 6),
y = c(5, 6, 6, 5))
DSB <- data.frame(x = c(1, 10, 10, 1),
y = c(1, 10, 1, 10))

plot(y ~ x, DSB, col = "red")
points(DSA, col = "blue")
for (r in seq_len(nrow(DSA))) {
segments(DSA\$x[r], DSA\$y[r], DSB\$x, DSB\$y)
}
``````

Edit: more directly:

``````nA <- nrow(DSA)
nB <- nrow(DSB)
plot(y ~ x, DSB, col = "red")
points(DSA, col = "blue")
segments(rep(DSA\$x, each = nB),  rep(DSA\$y, each = nB),
rep(DSB\$x, times = nA), rep(DSB\$y, times = nA))
``````

(I still can't figure out an elegant solution with @42's recommendation for `combn` or `outer`.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download