# [R] Trouble creating and adjacency matrix

Rolf Turner rolf.turner at xtra.co.nz
Mon Sep 26 05:30:26 CEST 2011

```See end of message.

On 26/09/11 10:07, Spartina wrote:
> Hello all,
>
> I'm having trouble creating an adjacency matrix.
>
> Basically, I need to turn the following distance matrix into an adjacency
> matrix based on whether values are>1.5 or not. If they are>1.5, then the
> returned value should be 0. If they are =<1.5, then the returned value
> should be 1.
>
> DistanceMatrix:
>
>             A             B          C             D          E
> [1,] 0.000000 2.828427 1.581139 2.236068 2.000000
> [2,] 2.828427 0.000000 1.581139 4.123106 2.000000
> [3,] 1.581139 1.581139 0.000000 2.549510 2.121320
> [4,] 2.236068 4.123106 2.549510 0.000000 4.123106
> [5,] 2.000000 2.000000 2.121320 4.123106 0.000000
>
> I'm trying to do this via the if statement, however I can't get it to work
> and it keeps returning an error message:
>
>> if(DistanceMatrix>1.5) {0} else {1}
> [1] 1
> Warning message:
> In if (DistanceMatrix>  1.5) { :
> the condition has length>  1 and only the first element will be used
>
>
> I am brand new to R and have a very limited knowledge of functions and
> syntax. Maybe the if statement is not even the right way of tackling this
> problem....

Well, you got that right.  It isn't.  Do:

AdjacencyMatrix <- 0 + (DistanceMatrix <= 1.5)

Note that the ``0 + '' bizzo is a trick to coerce a logical matrix
(entries "TRUE" or "FALSE") into a numeric matrix of 0-s and 1-s.

Learn to speak R.  It's worth the effort.

cheers,

Rolf Turner

```