x <- 10
if (x > 5) {
print("x is greater than 5")
}[1] "x is greater than 5"
Loops, Conditionals, Functions, and Beyond
Raju Rimal
June 11, 2026
Now that you’ve installed R and are familiar with its basic interface, it’s time to dive deeper into the core programming constructs that make R a powerful tool. This guide introduces conditionals, loops, functions, and other foundational concepts that will help you write efficient and reusable code. Mastering these basics will set the stage for more advanced topics like data manipulation and analysis.
Conditionals are essential for decision-making in code. They allow you to execute different actions based on certain conditions.
if StatementThe if statement checks a condition and executes the code inside its block if the condition is TRUE.
if...else StatementUse else to provide an alternative block of code when the condition is FALSE.
ifelse for Vectorized OperationsThe ifelse function applies a condition to every element of a vector.
Combine multiple conditions with if, else if, and else.
x <- -1
if (x > 0) {
print("Positive")
} else if (x == 0) {
print("Zero")
} else {
print("Negative")
}[1] "Negative"
Loops let you repeat a block of code multiple times, making them invaluable for automation.
for LoopIterates over a sequence of numbers, vectors, or lists.
while LoopExecutes as long as a condition is TRUE.
repeat LoopRepeats indefinitely until a break statement is encountered.
Use loops to iterate through more complex objects:
[1] "Apple"
[1] "Banana"
[1] "Cherry"
Functions allow you to encapsulate code logic, making it reusable and modular.
Use the function keyword to define your own functions.
You can set default values for function arguments.
Return a list to output multiple values from a function.
calculate <- function(a, b) {
sum <- a + b
product <- a * b
return(list(sum = sum, product = product))
}
result <- calculate(3, 5)
print(result$sum)[1] 8
[1] 15
Vectors are a fundamental data structure in R. R’s operations are vectorized, meaning you can perform operations on entire vectors at once.
apply Family of FunctionsInstead of using loops, R provides the apply, lapply, sapply, and other functions for applying operations to data structures.
apply on Matrices:lapply on Lists:numbers <- list(a = 1:3, b = 4:6)
# Calculate the sum of each element in the list
sums <- lapply(numbers, sum)
print(sums)$a
[1] 6
$b
[1] 15
A data frame is like a table where each column can have different types.
Extract rows, columns, or specific values.
Lists can hold different types of data.
[1] 90 85 88
R provides tools for handling errors gracefully.
tryCatchsafe_divide <- function(a, b) {
tryCatch({
result <- a / b
return(result)
}, warning = function(w) {
print("Warning occurred")
}, error = function(e) {
print("Error occurred")
})
}
safe_divide(10, 0)[1] Inf
x or y.apply functions whenever possible.Once you are comfortable with these programming concepts, you’re ready to explore more advanced topics like:
dplyrggplot2These foundations will make it easier to understand and implement sophisticated analysis techniques.
R’s programming fundamentals, like conditionals, loops, and functions, form the building blocks of your data journey. By mastering these concepts, you’ll be well-prepared to handle more complex data tasks with confidence.