Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to test if short numeric vector is a portion of long numeric vector in R

Tags:

r

I am trying to test if a short numeric vector is a portion of a longer numeric vector. For example, if a = c(2, 3) and b = c(1, 3, 2, 4, 2, 3, 1), then I'm trying to find / think of a function that would answer the question: is a a part of b? The output should be TRUE.

Alternatively, if c = c(1, 3, 2, 4, 1, 3, 1) then the output of "is a a part of c?" should be FALSE.

match() doesn't do the job:

match(a, b)

returns

3  2

Nor does the %in% operator:

TRUE  TRUE

I know there are options for string matching but I'd prefer not to work around this issue by converting to strings...

like image 508
CephBirk Avatar asked Dec 17 '25 17:12

CephBirk


1 Answers

Here's my crack at it

valInLong <- function(val, long){
  n.long <- length(long)
  n.val <- length(val)
  # Find where in the longer vector the first
  # element of val is.  This is so we can vectorize later
  first <- which(long == val[1])
  # If the first element is too near the end we don't care
  # about it
  first <- first[first <= n.long - n.val + 1]
  # sequence from 0 to n.val - 1 used for grabbing subsequences
  se <- seq_along(val)-1
  # Look at all subsequences starting at 'first' that go
  # the length of val and do an elementwise comparison.
  # If any match in all positions then the subsequence is
  # the sequence of interest.
  any(sapply(first, function(x){all(long[x+se] == val)}))
}


long <- rpois(1000, 5)
a <- c(123421, 232, 23423) # probably not in long

valInLong(a, long)
a <- long[34:100]
valInLong(a, long)
like image 170
Dason Avatar answered Dec 20 '25 08:12

Dason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!