Statement Condition pada Programming-R adalah :
1. If Statement
Format :
if(boolean_expression) {
// If the boolean expression is true, then statement(s) will be executed.
}
Contoh 1 :
x <-24L
y <- "kondisi"
if(is.integer(x))
{
print("x adalah Integer")
}
Contoh 2 :
x <-10
y<-34
count=0
if(x<y)
{
cat(x, "x lebih kecil dari y \n")
count=1
}
if(count==1){
cat("sukses diproses")
}
2. If-else Statement
Format :
if(boolean_expression) {
// statement(s) will be executed if the boolean expression is true.
} else {
// statement(s) will be executed if the boolean expression is false.
}
Contoh :
a<- 100
#checking boolean condition
if(a<20){
cat("a lebih kecil dari 20")
if(a%%2==0){
cat(" merupakan nilai genap\n")
}
else{
cat(" merupakan nilai ganjil\n")
}
}else{
cat("a lebih besar dari 20")
if(a%%2==0){
cat(" merupakan nilai genap \n")
}
else{
cat(" merupakan nilai ganjil\n")
}
}
3. else if Statement
Format :
if(boolean_expression 1) {
// This block executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// This block executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// This block executes when the boolean expression 3 is true.
} else {
// This block executes when none of the above condition is true.
}
Contoh :
marks=93;
if(marks>65){
print("Level 1")
}else if(marks>55){
print("Level 2")
}else if(marks>45){
print("Level 3")
}else{
print("Fail")
}
4. Switch Statement
Format :
switch(expression, case1, case2, case3....)
Contoh :
y = "18"
x = switch(
y,
"9"="Nilai 9",
"12"="Nilai 12",
"18"="Nilai 18",
"21"="Nilai 21"
)
print (x)
5. Next Statement
Format :
next
Contoh :
x <- 2:20
for (val in x) {
if (val == 3){
next
}
print(val)
}
6. Break Statement
Format :
break
Contoh :
v <- c("proses","loop")
count <- 4
repeat {
print(v)
count <- count + 1
if(count > 5) {
break
}
}