0

I am trying to build a for loop with a nested if statement to check for the maximum values in a vector. I hope to take this code and apply it to spectrum data.

Right now it's returning an error that I'm not sure how to troubleshoot. Do I need to break up my logical operators in my If statement?

Code:

r <- c(1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7)
Peaks <- c()
indPeaks <- c()
length(r)
for(x in length(r)) {
 if((r[x-1]<r[x] & r[x+1]<r[x])==TRUE){
    Peaks <-r[x]
    indPeaks <- which(r == r[x])
  }
}

Error in if ((r[x - 1] < r[x] & r[x + 1] < r[x]) == TRUE) { : missing value where TRUE/FALSE needed

Frank
  • 66,179
  • 8
  • 96
  • 180
Lil Coder
  • 23
  • 4
  • 1
    Please see [how to make a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Please do not post pictures of code and data. They should be included as text in the question itself. This makes it much easier to copy/paste to test the code and makes it easier to search later. – MrFlick Oct 02 '18 at 18:21
  • Agree with the previous comment about posting your code directly. That enables us to copy your code into a console and run it. – Adam Sampson Oct 02 '18 at 18:25
  • 2
    You have two problems. First `x in length(r)` only refers to one value...the last position available in `r`. Second, `r[x-1]` will return NA if x is 1, and `r[x+1]` will return NA if x is length(x) because there is no data outside of your vector. The results of NA < r[x] is NA...and you need TRUE or FALSE as a result. – Adam Sampson Oct 02 '18 at 18:28
  • Sorry about that, I edited the question and added the code. Just wanted to show the error I was getting. – Lil Coder Oct 02 '18 at 18:28
  • If this is for an assignment then fixing those problems should help. Otherwise you might want to look up the functions `max()` and `which.max()` which will be faster than a loop. – Adam Sampson Oct 02 '18 at 18:32
  • @AdamSampson Those are for global max, not local. I guess I'd look at `diff` and `sign` to find local maxes in a vectorized way. – Frank Oct 02 '18 at 18:34
  • Also you don't need the `== TRUE` part because `r[x-1] – see24 Oct 02 '18 at 18:50

0 Answers0