0

I'm trying to write a loop in R that finds and marks points in the set where the change in frequency is greater than a certain percentage. Heres's my code

change = c(1:length(df3$frequency)-1)
hold = c(1:length(df3$frequency))
for(i in 1:length(df3$frequency)-1){
  hold[i] = (df3$frequency[i+1] - df3$frequency[i])/df3$frequency[i]
  if(hold[i] < 0.004){
    change[i] = 'True'
  }
}

Error in if (hold[i] < 0.004) { : argument is of length zero

I've tried changing the percentage amount, and also changing the vector types. However I cannot understand the issue with the if statement.

  • Hi Jack! Welcome to StackOverflow! – Mark Aug 09 '23 at 14:58
  • 1
    A couple of thoughts: 1. it's going to be hard to diagnose for sure unless you say how long df3$frequency is; 2. you should replace `1:length(x)` with `seq_along(x)` – Mark Aug 09 '23 at 14:59
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 09 '23 at 15:07
  • 4
    Likely issue is that using `1:length(df3$frequency)-1` your loop starts at `i=0` and will therefore result in the mentioned error. You probably want `1:(length(df3$frequency)-1)`. – stefan Aug 09 '23 at 15:07
  • 1
    it would also be great if you could explain what you're trying to do. It's likely that there's a much faster, more concise, and easier to read version of it that uses vectorisation – Mark Aug 09 '23 at 15:27
  • Apart from what @stefan wrote in his comment, why not `change = character(length(df3$frequency)-1)` and `hold = numeric(length(df3$frequency))`? – Rui Barradas Aug 09 '23 at 15:29
  • Sorry I just realised it was a syntax issue in the for loop, the 1 was being subtracted from both the 1 and the length of the frequency, rather than just the length of the frequency. Thanks for your replies ! – jacksherry137 Aug 09 '23 at 15:39

0 Answers0