How to have two conditions in a While loop?

我是研究僧i 提交于 2019-12-11 06:18:29

问题


Basically I have two while loops in my code. All they do is count in increments of 1 from 0 to either 10 or -10. The vectors that count are "count1" and "count2". This is happening in my code in two separate while loops. However, I now need each count dependent on each other so I need them within the same loop. Is it possible to have the two separate while conditions working in one loop. For example, what I have now is:

  count1 = 0
  count2 = 0
  l_RWM = vector()
  r_RWM = vector()      


while (count1 < 10 && count1 > -10){

  count1 = count1 + (sample(c(1,-1), 1, prob = c(.55,.45)))

  l_RWM = append(l_RWM,count1)

}

while (count2 < 10 && count2 > -10){

  count2 = count2 + (sample(c(1,-1), 1, prob = c(.55,.45)))

  r_RWM = append(r_RWM,count2)

}

But I want something like

while (count1&count2 < 10 && count1&count2 > -10){

if(count1 < 10 && count1 > -10) count1 = count1 + (sample(c(1,-1), 1, prob = c(.55,.45)))
    else count1 = count1

  if(count2 < 10 && count2 > -10) count2 = count2 + (sample(c(1,-1), 1, prob = c(.55,.45)))
    else count2 = count2

    l_RWM = append(l_RWM,count1)
    r_RWM = append(r_RWM,count2)

 }

My "if" code is supposed to only have the count occur when the object hasn't reached 10 or -10. E.G. count2 will still count up or down even when count1 has finished. My code doesn't work and I am not looking for an answer but more so a reason to why it doesn't. Keeping in mind that I am very new to R and I apologise in advance if this question is trivial :p.

For anyone wondering, the reason I need them in the same loop is because I'm looking to have something like: if count1 increases than count2 decreases.

Thanks


回答1:


I am assuming, from your pseudo code, that you are just wanting to make sure both count1 and count2 are less than 10 and that count1 and count2 are greater than -10. What I would do is something like this:

while (count1 < 10 && count2 < 10 && count1 > -10 && count2 > -10){

You shouldn't need to group anything with parenthesis since everything is ANDed together and there is no mixed logic.



来源:https://stackoverflow.com/questions/21297582/how-to-have-two-conditions-in-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!