user2888902
user2888902

Reputation: 41

How to write a loop to find maximum value and its correspond lag value on condition

I just wrote a chunk to find out the largest spike in cross-correlation values, but when I ran the loop code there is no output at all. So I just want to ask if there's something wrong with my logic in writing loops or is there any thing I can try to revise the order.

My intended logic for output:

for (i in 1:n) {
  if (y[i]=max(y[i]) & x[i]>0) {
     p=x[i]
  }
  else if (y[i]=min(y[i] & x[i]<0) {
     p=-x[i]
  }
}

The rest else is omit because they input nothing. Please be note that x[i] and y[i] are in the same data frame.

Below is my code (I found I've made a big mistake for my d1 input):

Set Data Frame (I just uploaded the output of my ccf result):

lag<-c(-26:26)
acf<-c(0.047407605,-0.082137676,0.034121452,0.039142063,-0.043329145,-0.020623160,0.039402880,0.015249114,-0.035820024,-0.015923312,0.037330662,0.006072103,-0.031716579,0.011451683,-0.010197626,-0.002019121,0.053034576,-0.046888611,-0.014243574,0.062941934,-0.008920250,-0.069821500,0.055471320,-0.047680416,0.041748427,-0.397052734,0.753759104,-0.354801338,0.040349059,-0.082996566,0.093101698,-0.120570604,0.052011432,-0.007482147,0.045102472,-0.064384729,0.048119729,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
d1<-data.frame(lag,acf)

for(i in 1:length(d1[,2])) {
  if (d1[i,2] == max(d1[,2])) {
    if(d1[i,1]>0){
      cat(d[i,1])
      cat("CHIE lags CHIQ \n")
      p=d1[i,1]
      } else {
        if (d1[i,2] == min(d1[,2]) & d1[i,1]<0) {
          d=-d1[i,2]
          cat(d)
          cat("CHIE leads CHIQ \n")
          p=d
        }
      }
}

I am sorry that I do forget bunch of basic loop knowledge in C and want to take it back to my mind. Thanks a ton for your help!

P.S I test some basic data frame and it does work, but unluckily it does not work on my own data set (No error, but no output). So I guess if there's something wrong with the output of ccf function as well.

Upvotes: 2

Views: 2706

Answers (1)

lilster
lilster

Reputation: 933

There is no output in your code because you are missing a '}'. If there's no error message, it usually means you haven't closed the loop. Run the below and you'll see it works.

d1 <- data.frame(runif(100), runif(100))
colnames(d1) <- c('x','y')

for(i in 1:length(d1[,2])) {
  if (d1[i,2] == max(d1[,2])) {
    if(d1[i,1]>0){
      cat(d1[i,1])
      cat("CHIE lags CHIQ \n")
      p=d1[i,1]
  } else {
    if (d1[i,2] == min(d1[,2]) & d1[i,1]<0) {
      d=-d1[i,2]
      cat(d1)
      cat("CHIE leads CHIQ \n")
      p=d1
    }
  }
}
}

Yet there are more elegant ways to find the index of the maximum in each column. See ?which.max

tester <- apply(d1, FUN=which.max, 2)

Now you can use the values of tester[1] and tester[2] and replace the loop.

Upvotes: 2

Related Questions