4

I have two logical vectors which look like this:

x = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)

I would like to count the intersections between ranges of consecutive values. Meaning that consecutive values (of 1s) are handled as one range. So in the above example, each vector contains one range of 1s and these ranges intersect only once.

Is there any R package for range intersections which could help here?

Cos
  • 1,649
  • 1
  • 27
  • 50

1 Answers1

8

I think this should work (calling your logical vectors x and y):

sum(rle(x & y)$values)

A few examples:

x = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 1

x = c(1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 2

x = c(1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0)
y = c(0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 3

By way of explanation, x & y gives the intersections on a per-element level, rle collapses runs of adjacent intersections, and sum counts.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • This is a great answer, thank you! Any idea if I could somehow count only the intersections of the first vector? So for example x = c(0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) y = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0) would result in "1" intersection – Cos Dec 21 '19 at 10:23
  • Not nearly so easily... at least not with this method. I'd suggest asking a new question for that. I'd also suggest phrasing it as "counting at most one intersection per run of 1s in the first vector"--that seems clearer. – Gregor Thomas Dec 22 '19 at 17:49