[R] special recursive filter

Konrad Schubert infochat at gmx.net
Fri Jul 29 17:16:21 CEST 2011


Hi,
I have a question about a special recursive filter problem.

What I have:

- given variables:
  x: time series with rather randomly occuring '0' and '1'
  wait: non negative integer

- a working but ineffectiv implementation (see below)

How the implementation works (what I want):

The filter should drill holes of distance 'wait' between the '1' in x, e.g.

x = 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1
wait = 2

desired result:

result = 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1

working implementation:

  #*************************************************************************
  # basic informations
  #*************************************************************************

  # length of input vector
  lengthX <- length(x)

  # stop times for the recursive filter indices
  stopS <- 1:lengthX + wait - 1

  # initialize the result and the intermediate result vector
  # with additional length for recursive filtering
  result <- y <- numeric(lengthX + wait)

  #*************************************************************************
  # filter
  #*************************************************************************

  # recursive filter function
  for(i in 1:lengthX){

    # present ('x') and lag ('y') filtering
    ans <- x[i] + sum(y[i:stopS[i]])

    # check for the right filter answer
    if( ans == 1){
      y[wait + i] <- -1
      result[wait + i] <- 1
      }
  }

  #*************************************************************************
  # post calculation
  #*************************************************************************

  # remove the additional length for recursive filtering
  # from the returning vector
  result <- result[-(1:wait)]

-----------------------------------------------------------------------

Is there anyone how has a better idea?
Thank you for your help,
Thomas.
--



More information about the R-help mailing list