Other sites

Simple pattern detection in numerical data

(This article was first published on yaRb, and kindly contributed to R-bloggers)

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

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.