Control : for, if, ...



Flow control is accomplished using if, for, while, repeat and break statements with the following syntax..

  if(conditional) {expression}
  if(conditional) {expression} else {expression}
 
ifelse(conditional, true result returned, false result returned)
  for(variable in sequence) {expression}
  while(conditional) {expression}
  repeat {expression}
  break
Logical operands used in conditional expressions are

	==	equality
	!=	not equal
	||	or 
	&&	and

TRUE and FALSE are system defined variables to represent boolean states.

Samples

# An if statement. 
# Note that "else" is on the same line as the closing bracket.
# The if ... else statement won't parse otherwise.

if((i < 10)&&(i > 0))
{
    x[i] <- 10.0;
} else
{ 
    x[i]<- 20.0; 
    i   <- i+1;
}

# A for loop from i = 1 to i = 3 in increments of 1

for(i in (1:3))
{
    x[i] <- i;
    y[i] <- i-1;
}

# A for loop from i = 5 to i = 1 in increments of -1

for(i in seq(5,1,-1))
{
    x[i] <- i;
}

# A repeat statement with a break to exit

i <- 20;
repeat
{
    cat(i," ");
    i <- i-1;
    if(i < 0) break;
}

# A while loop 

i <- 20;
while( i > 0 )
{
    cat(i," ");
    i <- i-1;
}

Original Documentation : control, ifelse, switch, seq.

UCLA Mathematics Department ©2000