R Loops and Apply Functions
Loops are used to iterate over a sequence of elements, while the apply family of functions provides efficient alternatives to loops for certain operations.
Key Topics
Loops
# Using a for loop
for (i in 1:5) {
print(i)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 2
[1] 3
[1] 4
[1] 5
Code Explanation: The for
loop iterates over the numbers 1 to 5, printing each number.
Apply Functions
The apply()
family of functions includes apply()
, lapply()
, and sapply()
for applying functions to elements of arrays, lists, or vectors.
# Using lapply
list_data <- list(a = 1:3, b = 4:6)
result <- lapply(list_data, sum)
print(result)
Output:
$a
[1] 6
$b
[1] 15
[1] 6
$b
[1] 15
Code Explanation: The lapply()
function applies the sum
function to each element of the list, returning a list of results.
Key Takeaways
- Use loops for iterating over elements when necessary.
- The
apply()
family of functions provides efficient alternatives to loops. lapply()
andsapply()
are commonly used for list and vector operations.