[R-sig-eco] construct a nearest neighbor contingency table

Jari Oksanen jari.oksanen at oulu.fi
Wed Jun 4 06:38:41 CEST 2008


Quoting Sarah Goslee <sarah.goslee at gmail.com>:

> What about using dist() on the xy coordinates, then finding the minimum
> for each row? That would get you nearest neighbor for each site.
>
This suggests the following code:

> gender <- sample(c("female","male","unknown"), 50, repla=T,  
> prob=c(0.5, 0.4,0.1))
> coord <- matrix(runif(100), nrow=50)
> m <- as.matrix(dist(coord))
> diag(m) <- NA>
nn <- apply(m, 1, which.min)
> table(gender, gender[nn])

gender    female male unknown
   female      18    8       2
   male         9    2       5
   unknown      2    4       0

Which surely is doable and even straightforward, and supports R's  
reputation as an environment where you can do anything, but not easily.

An alternative is to install spdep package (spatial dependence) which  
has a fucntion called knearneigh:

> table(gender, gender[knearneigh(coord, k=1)$nn])

gender    female male unknown
   female      18    8       2
   male         9    2       5
   unknown      2    4       0

The drawback is spdep is very heavy and requires many other packages.  
On the other hand, you get many new things if you want to have spatial  
analysis.

cheers, jari oksanen

>
> On Tue, Jun 3, 2008 at 7:28 PM, Tom Elliott <tnelliott at gmail.com> wrote:
>> Hello-
>>
>> I have plot data of  mapped male and female cottonwoods, collected for
>> my master's thesis. The data are multiple rows in 3 columns:
>> x-coordinate, y-coordinate, and a code for male, female, or unknown. I
>> want to test it for spatial segregation of the sexes using methods by
>> Phillip Dixon (1994, 2002).
>>
>>  Is there a way in R to build a nearest neighbor contingency table for
>> the data? I would like the format to be 3 rows (male, female,
>> unknown), with columns for counts of the nearest neighbors in each
>> class.
>>
>> Thanks,
>> Tom
>>
>
> --
> Sarah Goslee
> http://www.functionaldiversity.org
>
> _______________________________________________
> R-sig-ecology mailing list
> R-sig-ecology at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-ecology
>



More information about the R-sig-ecology mailing list