[R] overlap between line segments

Jim Lemon drjimlemon at gmail.com
Tue Jul 14 12:03:12 CEST 2015


Hi Karla,
This might help. I haven't tested it exhaustively.

transect_overlap<-function(x) {
 if(!is.matrix(x)) stop("x must be a 2x2 matrix")
 if(x[1,1] <= x[2,1]) {
  if(x[2,2] > x[1,2]) overlap<-x[1,2]-x[2,1]
  else overlap<-x[2,2]-x[2,1]
 }
 else {
  if(x[1,2] > x[2,2]) overlap<-x[2,2]-x[1,1]
  else overlap<-x[1,2]- x[1,1]
 }
 if(overlap < 0) overlap<-0
 return(overlap)
}

Jim


On Tue, Jul 14, 2015 at 7:44 AM, Karla Shikev <karlashikev at gmail.com> wrote:
> Hi there,
>
> This is a newbie question, and I'm sure there are simple ways to do this,
> but I've spent my entire afternoon and I couldn't get it to work.
>
> Imagine that I got my samples distributed along a transect and my data
> refer to the first and last occurrences of each sample. For instance:
>
>> dat<-matrix(c(1,3,2.5,4), ncol=2, byrow=TRUE)
>> dat
>      [,1] [,2]
> [1,]  1.0    3
> [2,]  2.5    4
>
>
> The first line indicates that the first and last occurrences of this
> subject were 1 and 3, respectively, whereas the second subject was found
> between 2.5 and 4.
>
> I need a simple way to calculate the overlap of their extents (0.5 in this
> case). This way should provide 0 if there is no overlap, and it should also
> work in the case where one subject is found only within the extent of the
> second subject.
>
> Any help will be greatly appreciated.
>
> Karla
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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