Simple pattern detection in numerical data

A while ago I helped out a colleague who was testing some methods to detect economic (in)activity of companies, based on their quarterly tax declarations (our institute has access to such data). One of the thing my colleague wanted was to detect simple patterns, such as a bunch of zero-declarations, followed by positive ones, or the other way around. After fiddling around for half an hour I came up with the following solution which is so "typically R" that I decided share it, so here it goes.

In stead of directly detecting the patterns, I decided to write a distance function which counts the number of cells in a row which do not comply with some pattern. A pattern can be specified with

 1 (value is positive)
-1 (value is negative)
 0 (value is zero)
NA (value is missing)

A vector of values indicates a pattern. Below is the function:

Created by Pretty R at

The type of numbers to be detected was so simple that it was sufficient to use the sign function. Also, it's kinda funny to note that the whole function consists of a single apply-statement (which is never a goal in itself of course, but nevertheless...). I think it is a nice example of the power of R. Here's an example of how to use it.

Created by Pretty R at

And indeed, only the first row completely complies with the pattern negative-positive-positive-missing.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

9 × three =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">