如何在r中创建条件循环?

时间:2013-12-12 12:48:31

标签: r

我希望做到以下几点:

  if  X>Y and 
      Z>A and
      B>Y then print ("SUCCESS")
else LOAD NEXT VARIABLES AND REPEAT 

在r中最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

X = 2
Y = 1
Z = 4
A = 2
B = 2

if( X > Y & Z > A & B > Y){
  print("SUCCESS")
  }else{
  print("do somethng else")
}

# similarly
#if( X > Y && Z > A && B > Y){
#  print("SUCCESS")
#  }else{
#  print("do somethng else")
#}
###################################

要重复此功能,可能更容易:

repeat{
  X = sample(1:10, 1)
  Y = sample(1:10, 1)
  Z = sample(1:10, 1)
  A = sample(1:10, 1)
  B = sample(1:10, 1)
  if( X > Y & Z > A & B > Y){
    print("success")
    break
  }
 }

致力于这种逻辑:

n = 1

repeat{
 print("success")
 n <- n+1
  if( n > 10){
    print("stop now")
    break
  }
 }
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "success"
#[1] "stop now"