Search code examples
rfor-loopseqauc

R: loop won't run due to a seq.default error


I am trying to calculate the area under the curve for every 10ms of a short piece of EEG wave. To first practice this I made a small dataset to run the auc (from package {flux}) function on.

x <- seq(1:10)
y <- c(0:4,5:1)
df <- data.frame(x,y)
attach(df)
plot(x,y)

for (i in 1:10){
  x1 <- c(i,(i+1))
  y1 <- c(subset(y, x == i),subset(y, x == (i+1)))
auc(x1,y1,thresh = 0)
rm(y1,x1,i)
}

The loop should try to subset two data points from each variable and then run a auc over those data points. However, when running the loop, I get this error: Error in seq.default(x[1], x[2], length.out = dens) : 'to' must be a finite number

When I run the subset and auc code outside of the loop, it works no problem. Can anyone tell me what's going wrong in the loop?


Solution

  • Thanks for updating the question. It's not because of the control statement (for loop), the error gets thrown precisely when i=10 -- because the length of your x-coords and y-coords vectors are different. Specifically c(10,11) vs c(1). But you have no point at x=11 !

    just stop the loop early, at the appropriate time