mardi 6 octobre 2015

In R: if statement gives 'missing value where TRUE/FALSE needed' error, but there are no missing values

I have written a function to identify peaks in a series of acceleration values. (I am aware of the quantmod package & findPeaks function, but it doesn't identify peaks according to my criteria.) I want to identify a peak as any value that follows three consecutive increases and precedes three consecutive decreases.

Here is my function... I apologise if it is very inelegant, but it's my first attempt at doing this. The vector x is a series of about 900-1200 acceleration values; e.g. 1.003841, 1.003570, 1.003428, 1.003261, 1.003033, 1.002630...

peakFinder <- function(x){
  diffs <- sign(diff(x))
  lags <- 1:length(diffs)
  frame <- data.frame(diffs, lags)
  frame$diffs <- ifelse(is.na(frame$diffs), 0, frame$diffs)
  pks <- 0

  for(l in frame$lags){
    if ((frame[l,1] == 1) & (frame[l+1,1] == 1) & (frame[l+2,1] == 1) 
      & (frame[l+3,1] == -1) & (frame[l+4,1] == -1) & (frame[l+5,1] == -1)){
      pks <- c(pks, l+2)
    }
  }
  pks <- pks[-1]
  pks
  }

The if statement keeps giving me the error "missing value where TRUE/FALSE needed". This is confusing because there are no missing values in either frame$diffs or frame$lags. I am probably making some other basic error, but I can't figure out what it is.

I would really appreciate some help!

Aucun commentaire:

Enregistrer un commentaire