-4

I am trying to write a program using a while loop:

(UPDATE: solution founded!! since there must be a true/false statement provided in the below part), The if function should be clear justification.

while ((it_count) < it_max && it_change > tol)
     {

    wj <- Kc%*%yj               #LS regression for wj
    vj <- wj/as.vector(t(wj)%*%wj)      #normalization of wj
    cj <- t(yj)%*%vj            #LS regression for cj
    old_yj <- yj
    yj <- yj%*%cj
    yj <- yj/as.vector(t(yj)%*%yj)      #normalize new yj
    diff_y <- yj - old_yj
    it_change <- diff_y/as.vector(t(diff_y)%*%diff_y)
    it_count <- inc(it_count)
     }

    if (a == j ) break 
    else 
    {warning(paste("failed to converge for component", a, "steps"))}
Honstel
  • 29
  • 4
  • You only need a single `&` character for the AND opetator – Rohit Sep 10 '18 at 06:14
  • @Rohit: `&&` works differently to a single `&`, as it returns only a single result even when you apply it to vectors. It's often a better choice for `if` clauses. – Marius Sep 10 '18 at 06:23
  • Yes and no, the single `&` does element-wise comparisons and thus return a n-length logical vector, while double `&&` will always return a single TRUE/FALSE by evaluating left-to-right the first element. Neither will however change the error presented here. – MrGumble Sep 10 '18 at 06:24
  • 2
    The error occurs because one of the variables in `(it_count) < it_max && it_change > tol` is an `NA`, thus either comparison evalutes to `NA`, which is neither TRUE nor FALSE. – MrGumble Sep 10 '18 at 06:25
  • hello all, I provided the full code that used in the algorithm – Honstel Sep 10 '18 at 06:26
  • @SalmanLashkarara - comparisons (`>` and `<`) takes precendence over and and or (https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html), so it shouldn't change the outcome. But it could improve readability. – MrGumble Sep 10 '18 at 06:28
  • @Honstel But you not gave example data. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example Beside of that your code is not minimal; [mcve] – jogo Sep 10 '18 at 06:29
  • why dont you satrt by cleaning your code? – Sal-laS Sep 10 '18 at 06:35

1 Answers1

1

It seems as though something about your condition in the while statement isn't returning a TRUE or a FALSE like it should. From the chunk of code you've shared, it doesn't tell us how it_max or tol is defined. Given it runs but returns something that isn't a TRUE or FALSE, I suspect one (or both) of them are an NA or NULL. Make sure they're declared and this should work.

If it still doesn't work, upload the code where these are declared and we can help more.

LachlanO
  • 1,152
  • 8
  • 14