UNIT-II: R-Control Structures and Functions
Decision Making in R
R provides several conditional statements:
- if(condition) { ... }
- if-else
- if-else ladder
- switch(expression, case1, case2, ...)
Example:
```R
x <- 5
if (x > 0) {
print("Positive")
} else {
print("Non-positive")
```
Switch Statement
Used for selecting one of many options:
```R
x <- 2
result <- switch(x, "One", "Two", "Three")
print(result)
UNIT-II: R-Control Structures and Functions
```
Loops in R
There are 3 main loop types:
- repeat: Infinite loop, must be broken with break.
- while: Runs while condition is TRUE.
- for: Iterates over a sequence.
Examples:
```R
# repeat
x <- 1
repeat {
print(x)
x <- x + 1
if (x > 5) break
# while
x <- 1
while (x <= 5) {
print(x)
x <- x + 1
UNIT-II: R-Control Structures and Functions
# for
for (i in 1:5) {
print(i)
```
Loop Control Statements
- break: Exits the loop.
- next: Skips current iteration.
Example:
```R
for (i in 1:5) {
if (i == 3) next
print(i)
```
R Functions - Definition
Functions in R are defined using the function keyword.
Example:
UNIT-II: R-Control Structures and Functions
```R
add <- function(a, b) {
return(a + b)
print(add(2, 3))
```
Function Calls
Functions can be called using their name and arguments.
They support default values and named arguments.
Example:
```R
greet <- function(name = "User") {
print(paste("Hello", name))
greet("Alice")
greet()
```
Lazy Evaluation
R evaluates function arguments only when needed.
Example:
UNIT-II: R-Control Structures and Functions
```R
demo <- function(x, y) {
print(x)
demo(10)
# y is never evaluated
```
Return Statement
Used to return values from functions.
```R
square <- function(x) {
return(x^2)
print(square(4))
```
Multiple Returns
Use lists to return multiple values.
```R
calc <- function(a, b) {
return(list(sum = a + b, product = a * b))
res <- calc(2, 3)
UNIT-II: R-Control Structures and Functions
print(res$sum)
```
Recursive Functions
A function calling itself is recursive.
Example:
```R
factorial <- function(n) {
if (n == 1) return(1)
return(n * factorial(n - 1))
print(factorial(5))
```