0

I 'm using the function below to put the items of a vector in an ascending order.

InOrder <- function(vector){
  le <- length(vector)
  for (j in c(2:le)){
    key <- vector[j]
    i <- j-1
    while (i>0 & vector[i]>key){
      vector[i+1] <- vector[i]
      i <- i-1
    }
    vector[i+1] <- key
  }
  vector
}

I have those vectors:

MyVector1 <- c(2,4,3,8,9)
MyVector2 <- c(5,4,3,8,9)

As you can see InOrder() function works fine with MyVector1:

MyVectorOrd1 <- InOrder(MyVector1)
MyVectorOrd1
[1] 2 3 4 8 9

but not with MyVector2:

MyVectorOrd2 <- InOrder(MyVector2)
Error in while (i > 0 & vector[i] > key) { : argument is of length zero

What am I doing wrong? I think that condition MyVector2[1]>MyVector2[2] causes that problem, but I don't know why.

Thanks' in avance!

PS: I 've read this question, but I couldn't find the problem in my code.

  • 1
    When it fails, what is the value of `i`, `vector[i]`, and `key`? If any of them are `NA`, then your condition will fail. (BTW: don't use single-`&` in `if`, `for`, or `while` loop in this way; it is useful when you are also using `all`/`any` (not applicable here), but not in ways like this. Use double-`&&` instead.) – r2evans Jan 24 '21 at 14:07
  • @r2evans , thanks a lot!!! The problem was `&`. I changed it to `&&` and problem fixed! Thanks! PS: Why that was a problem? – Kώστας Κούδας Jan 24 '21 at 14:14
  • 1
    Because the single `&` evaluates the whole expression and return a bolean vector. In yout case `vector[0]` returns NA. The double `&&` evaluates from left to right element by element and stops if the condition is no longer `TRUE` (so `i> 0 == FALSE` then stop) – Leonardo Jan 24 '21 at 14:19
  • 1
    @Leonardo, your second point about `&&` is spot-on: it supports [short-circuit logic](https://stackoverflow.com/a/6559049/3358272) that single-`&`/`|` do not. – r2evans Jan 24 '21 at 14:44
  • 1
    In the code, add `print(i)` below `i – Leonardo Jan 24 '21 at 14:49
  • @r2evans , thanks for your answers! I 'm new in R, you were very helpfull! – Kώστας Κούδας Jan 24 '21 at 18:46
  • @Leonardo , I know that many `i`s will be the same again and again. I make them like this (`i`=j-1, j-2, j-3,... for every j>3). Was it a problem? I know that wasn't the best algorithm, I 'm just exploring R and my knowledge. – Kώστας Κούδας Jan 24 '21 at 18:50
  • 1
    No problem! My answer was related to a comment from @r2evans. It is right that you do your tests with any kind of algorithm. – Leonardo Jan 24 '21 at 18:59
  • @Leonardo. Thanks for your answer! I was asking because sometimes I don't know where the error comes from. Everything seems good, but the reality was that I didn't see the error. I have a lot of pain like this in LaTeX... Thanks for your answer! – Kώστας Κούδας Jan 24 '21 at 19:14

0 Answers0