[R] Help with programming a tricky algorithm

Rui Barradas ruipbarradas at sapo.pt
Sun Oct 21 12:05:29 CEST 2012


Hello,

The function in my previous post gives neighbours in north, south, east 
and west but also the corners, for a total of 8, not 4, neighbours. 
Corrected:

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


Rui Barradas
Em 20-10-2012 11:11, Rui Barradas escreveu:
> 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,
>
> Rui Barradas
> 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
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list