[R] Help with programming a tricky algorithm

Sat Oct 20 12:11:40 CEST 2012

```Hello,

You should post a data example with ?dput. If your dataset is named
MyData, use

dput( head(MyData, 30) )  # paste the output of this in a post

Anyway, I believe the following function might do what you want. It's
untested, though. (Your example dataset is usefull but could be better)

is.border <- function(idx, DF){
ix <- DF\$ix %in% DF\$ix[idx] + c(-1, 1)
iy <- DF\$iy %in% DF\$iy[idx] + c(-1, 1)
any(DF\$country != DF\$country[ix & iy])
}

sapply(MyData\$idxy, fun, MyData)

It returns a logical value, so if you want 0/1 use as.integer to do the
conversion.

Hope this helps,

Em 20-10-2012 08:36, Andrew Crane-Droesch escreveu:
> Hi All,
>
> I'm a little stumped by the following problem.  I've got a dataset
> with the following structure:
>
> idxy    ix    iy    country    (other variables)
> 1        1    1    c1            x1
> 2        1    2    c1            x2
> 3        1    3    c1            x3
> .        .        .       .            .
>
> 3739    55    67    c7        x3739
> 3740    55    68    c7        x3740
>
> where ix and iy are interger-valued indices of the actual x and y
> coordinates for the gridded data
>
> I want to define a "border" variable that equals 1 if the cell north,
> east, west, or south of it has a different value of the country
> variable.  So, for the row with idxy = 1, border would equal 1 if
> there is any idxy with country !=c1 and ix = 2 (or zero) or iy = 2 (or
> zero).
>
> Any thoughts?
>
> Thanks!
> Andrew
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help