Control Statements in R
Control Statements in R
Raju N
If Statement
The syntax of R if statement is:
if (expression)
{
statement
}
If the expression is TRUE, the statement gets
executed. But if it is FALSE, nothing happens.
Example
x <- 100
if(x > 0)
{
print("This is Positive number")
}
if else statement
The syntax of if…else statement in R is:
if (expression)
{
statement1
}
else
{
statement2
}
Example
x <- -10.56
if(x >= 0)
{
print("This is Non-negative number")
} else
{
print("This is Negative number")
}
Nested if else statement
In nested if… else statements we can impose as many else if conditions as we
require
The syntax of nested if…else statement is:
if (expression1)
{
statement1
}
else if (expression2)
{
statement2
}
else if (expression3)
{
statement3
}
else
statement4
Example 1
x <- 5
if (x < 0)
{
print("This is Negative number")
} else
if (x > 0)
{
print("This is Positive number")
} else
print("This is Zero")
Example 2
• Marks <- 85
• if (Marks >=75)
• {
• print("Passed With First class and Distinction")
• } else
• if (Marks >=60)
• {
• print("Passed In First Class")
• } else
• if (Marks >=50)
• {
• print("Passed In Second Class")
• }else
• if (Marks >=35)
• {
• print ("Passed in Third Class")
• }else
• print("Failed")
For loop in R
for(i in c(-5,-3,0,1,2,3,4,1.3))
{
print(i^2)
}
Aliter
x= c(-5,-3,0,1,2,3,4,1.3)
for(i in x){print (i^2)}
i and i^2 together