Luke - 4 months ago 50

R Question

I have a dataset of XY points that looks like this

`x<-c(2,4,6,3,7,9,1)`

y<-c(6,4,8,2,9,6,1)

id<-c("a","b","c","d","e","f","g")

dataset<-data.frame(cbind(x,y,id))

I would like to connect

In "attributes table" that results from the output, names for spatial lines might look like this:

`a_b`

a_c

a_d

a_e

a_f

a_g

b_a

b_c

b_d

b_e

b_f

b_g

c_a

etc.

Answer

I'm speculating a bit here as to what exactly you wanted, but I think you want to visualize the connections from any point to the others. If that's the case, then this might work. But first, some assumptions:

- Your
`x`

and`y`

coordinates are starting points. Consequently,`id`

are thus`id.origin`

- All other points will need to become "destinations", and then their own coordinates will become
`x_destination`

and so on.

< disclaimer> There **should be** a better, more elegant way to do this. I'd appreciate if someone more experienced can jump in and show me any of the `*ply`

ways to do it. < /disclaimer>

Replicate the dataframe to cover for all possible combinations

```
dataset<-do.call(rbind, replicate(7, dataset, simplify=FALSE))
```

Now, create a matrix with all the same destination points, mixed:

```
nm=matrix(ncol=3)
for (i in 1:7){
nm<-rbind(nm,do.call(rbind,replicate(7,as.matrix(dataset[i,]),simplify=FALSE)))
}
nm<-nm[-1,]
```

Rename the columns of matrix, so they make sense, and bind the existing data frame with the new matrix

```
colnames(nm)<-c("x2","y2","id.dest")
newds<-cbind(dataset,as.data.frame(nm))
```

Remove duplicated trajectories:

```
newds<-newds[-which(newds$id.origin==newds$id.dest),]
```

and plot the result using `geom_segment`

:

```
p<-ggplot(newds,aes(x=x,y=y))+geom_segment(aes(xend=x2,yend=y2))
```

There is a way to name the segments, but from observing the plot I would't suggest doing it. Instead you might consider naming the points using `geom_text`

(other options are available, see `?annotate`

for one).

```
p<-p + geom_text(aes(x=1.8,y=6.1,label="a"))
```

That will produce a plot like the one here: