matching sub-vectors?

14 views
Skip to first unread message

amit gal

unread,
Aug 18, 2018, 12:47:58 AM8/18/18
to israel-r-...@googlegroups.com

so R has a great function, match, to find values in vectors (also %in% to test the existence). but what if I want to find a short vector in a big vector? that is, to test if a given vector is contained (in order!) in another vector? what if I want to find whether a given vector is a prefix/suffix of another vector? are there such functions in R?

example of what I would like:

x=c(1,3,4)
y=c(4,1,3,4,5)
z=c(3,1)

v_contains(x,y)  # return TRUE x is contained in y
v_contains(z,y)  # FALSE the values of z are in y, but not in the right order
v_match(x,y)     # returns 2 because x appears in y starting at position 2

is there anything like it? how would you approach it efficiently?


Michael Dorman

unread,
Aug 18, 2018, 3:42:32 AM8/18/18
to israel-r-...@googlegroups.com
If the vectors are always composed of single-digit numbers then I would use paste0(x, collapse = "") on both vectors and then gsub. This approach is also applicable with longer numbers if we add leading zeros before using paste0, but perhaps will be less efficient. Otherwise would look for a C/C++ function and use it with Rcpp. 

--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-group+unsub...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

amit gal

unread,
Aug 18, 2018, 4:41:26 AM8/18/18
to israel-r-...@googlegroups.com
the string method is not applicable in my case due to efficiency.

However after some thought, I did exploit another property of my vectors - in each vector values do not repeat

so for x to be fully contained in y
match(x,y) must be a series of consecutive numbers
so
all(diff(match(x,y))==1)
does what I need.



To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-group+unsubscribe...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Michael Dorman

unread,
Aug 18, 2018, 4:49:32 AM8/18/18
to israel-r-...@googlegroups.com
Good idea!
Reply all
Reply to author
Forward
0 new messages