简体   繁体   中英

R nested if statements error “condition has length > 1 and only the first element will be used”

I'm trying to do many conditional events in R but im getting the warning:

Warning messages:
1: In if (closeV > openV) { :
  the condition has length > 1 and only the first element will be used
2: In if ((highV - closeV) < Minimum) { :
  the condition has length > 1 and only the first element will be used
3: In if ((openV - lowV) > Threshold) { :
  the condition has length > 1 and only the first element will be used
4: In if (((openV - lowV) < Threshold)) { :
  the condition has length > 1 and only the first element will be used
5: In if ((closeV - openV) < Threshold) { :
  the condition has length > 1 and only the first element will be used
6: In if ((closeV - lowV) < (Threshold * 2)) { :
  the condition has length > 1 and only the first element will be used

this is a huge nest of ifs, it is not optimized right now but i cant get it to work because of that warning. There are around of 40 ifs in that function, any idea of what i need to do to get around this warning? The code looks something like this

  if(closeV>openV)#1 First we check if we have a positive value
  {
    if((highV-closeV)<Minimum)
    {
      if((openV-lowV) >Threshold)
      {
        if((closeV-openV)<Threshold)
        {
          #3.1 This is a Hammer with positive movement
          if((closeV-lowV)<(Threshold*2))
          {
            #3.1.1 not much movement
            return(X*2)
          }
          else if((closeV-lowV)>(Treshold*2))
          {
            #3.1.2 a lot of movement
            return(X*3)
          }

        }
        else if((closeV-openV)>Threshold)
        {
          #3.2 Hammer but with a lot of movement 
          if((closeV-lowV)<(Threshold*2))
          {
            #3.2.1 not much movement
            return(X)
          }
          else if((closeV-lowV)>(Treshold*2))
          {
            #3.2.2 a lot of movement
            return(X*5)
          }
        }        

      }
      else if(((openV-lowV)<Threshold)

and it keeps on going through a lot of possibilites

The issue is not the nested if-statements, but rather the data structure you feed into them: The warning tells you that the comparison operator is only applied to the first element of the data structure you feed into the if-statements.

While

a = seq(1, 10, 1)
b = seq(0, 18, 2)

if (a>b){
  print(a)
} else{
  print(b)
}

throws the same warning messages you get,

a = seq(1, 10, 1)
b = seq(0, 18, 2)

for (i in 1:10) {
  if (a[i]>b[i]){
    print(a[i])
  } else{
    print(b[i])
  }
}

in contrast evaluates smoothly.

Also, please notice that although both pieces of code are evaluated, they give very different results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM