0

I am working on a data frame with x and y columns with values as rows.. I want to calculate the slope of x and y for every 2 rows and then using the calculated slope, record whether slope's "stability" is "high" or "low". You'll understand better after seeing the code. What is wrong with this code? When I input stability, R returns NULL.

slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
stability <- c()
for (i in 1:nrow(acc)) {
  if (slope[i] > 0 & slope[i] < 0.8) {
    stability[i] <- "low"
  } else if (slope[i] >= 0.8 & slope[i] <= 1) {
    stability[i] <- "high"
  } else if (slope[i] > 1 & slope[i] < 1.2) {
    stability[i] <- "high"
  } else if (slope[i] >= 1.2) {
    stability[i] <- "low"
  } else if (slope[i] >= -1 & slope[i] <= -0.8) {
    stability[i] <- "high"
  } else if (slope[i] >= -0.8 & slope[i] <= 0) {
    stability[i] <- "low"
  } else if (slope[i] < -1 & slope[i] > -1.2) {
    stability[i] <- "high"
  } else 
    stability[i] <- "low"
}

1 Answers1

0

Modify your code as following:

    #slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
     stability <- as.vector(nrow(acc))       
    n <- nrow(acc)-1
    for (i in 1:n) {
      slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])         

      if (slope > 0 && slope < 0.8) {
        stability[i] <- "low"
      } else if (slope >= 0.8 && slope <= 1) {
        stability[i] <- "high"
      } else if (slope > 1 && slope < 1.2) {
        stability[i] <- "high"
      } else if (slope >= 1.2) {
        stability[i] <- "low"
      } else if (slope >= -1 && slope <= -0.8) {
        stability[i] <- "high"
      } else if (slope >= -0.8 && slope <= 0) {
        stability[i] <- "low"
      } else if (slope < -1 && slope > -1.2) {
        stability[i] <- "high"
      } else
        stability[i] <- "low"
    }

Try it Online

M.Hassan
  • 10,282
  • 5
  • 65
  • 84
  • You need to have `()` over `nrow(acc) - 1`. As it is now, `i` starts with `0`, not 1. – kangaroo_cliff Jul 08 '17 at 00:15
  • I set the counter to n <- nrow(acc)-1, thanks for hint – M.Hassan Jul 08 '17 at 01:52
  • @ Disco Superfly , n starts with 1, bez for (i in 1:n), try the demo – M.Hassan Jul 08 '17 at 12:38
  • That is because the code is edited now. See your previous comment where you thanked me for the hint... – kangaroo_cliff Jul 09 '17 at 00:39
  • @ Disco Superfly, I mean by my comment that loop start with 1 bez it's declared in the body of "for" statement, see my old revisions: https://stackoverflow.com/revisions/44981210/1 , https://stackoverflow.com/revisions/44981210/2. I modified the code (nrow(acc)-1) to be enclosed between braces to avoid error, and -1 affect the end of the loop, and I'm still thank you:) – M.Hassan Jul 09 '17 at 11:49