Looping over Objects in R Programming - GeeksforGeeks

02 Aug, 2020
Prerequisite: Data Structures in R Programming
One of the biggest issues with the “for” loop is its memory consumption and its slowness in executing a repetitive task. And when it comes to dealing with large data set and iterating over it, for loop is not advised. R provides many alternatives to be applied to vectors for looping operations that are pretty useful when working interactively on a command line. In this article, we deal with apply() function and its variants:
apply()
lapply()
sapply()
tapply()
mapply()
Let us see what each of these functions does.
apply(): This function applies a given function over the margins of a given array.apply(array, margins, function, ...)array = list of elementsmargins = dimension of the array along which the function needs to be appliedfunction = the operation which you want to performExample:# R program to illustrate# apply() function  # Creating a matrixA = matrix(1:9, 3, 3)print(A)  # Applying apply() over row of matrix# Here margin 1 is for row r = apply(A, 1, sum)print(r)  # Applying apply() over column of matrix# Here margin 2 is for columnc = apply(A, 2, sum)print(c)Output:[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

[1] 12 15 18
[1]  6 15 24

apply(array, margins, function, ...)
array = list of elementsmargins = dimension of the array along which the function needs to be appliedfunction = the operation which you want to perform
Example:
# R program to illustrate# apply() function  # Creating a matrixA = matrix(1:9, 3, 3)print(A)  # Applying apply() over row of matrix# Here margin 1 is for row r = apply(A, 1, sum)print(r)  # Applying apply() over column of matrix# Here margin 2 is for columnc = apply(A, 2, sum)print(c)
Output:
[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

[1] 12 15 18
[1]  6 15 24

lapply(): This function is used to apply a function over a list. It always returns a list of the same length as the input list.lapply(list, function, ...)list = Created listfunction = the operation which you want to performExample:# R program to illustrate# lapply() function  # Creating a matrixA = matrix(1:9, 3, 3)  # Creating another matrixB = matrix(10:18, 3, 3)   # Creating a listmyList = list(A, B)  # applying lapply()determinant = lapply(myList, det)print(determinant)Output:[[1]]
[1] 0

[[2]]
[1] 5.329071e-15

lapply(list, function, ...)
list = Created listfunction = the operation which you want to perform
Example:
# R program to illustrate# lapply() function  # Creating a matrixA = matrix(1:9, 3, 3)  # Creating another matrixB = matrix(10:18, 3, 3)   # Creating a listmyList = list(A, B)  # applying lapply()determinant = lapply(myList, det)print(determinant)
Output:
[[1]]
[1] 0

[[2]]
[1] 5.329071e-15

sapply(): This function is used to simplify the result of lapply(), if possible. Unlike lapply(), the result is not always a list. The output varies in the following ways:-If output is a list containing elements having length 1, then a vector is returned.If output is a list where all the elements are vectors of same length(>1), then a matrix is returned.If output contains elements which cannot be simplified or elements of different types, a list is returned.sapply(list, function, ...)list = Created listfunction = the operation which you want to performExample:# R program to illustrate# sapply() function  # Creating a listA = list(a = 1:5, b = 6:10)  # applying sapply()means = sapply(A, mean)print(means)Output:a b
3 8
A vector is returned since the output had a list with elements of length 1.
If output is a list containing elements having length 1, then a vector is returned.
If output is a list where all the elements are vectors of same length(>1), then a matrix is returned.
If output contains elements which cannot be simplified or elements of different types, a list is returned.
sapply(list, function, ...)
list = Created listfunction = the operation which you want to perform
Example:
# R program to illustrate# sapply() function  # Creating a listA = list(a = 1:5, b = 6:10)  # applying sapply()means = sapply(A, mean)print(means)
Output:
a b
3 8

A vector is returned since the output had a list with elements of length 1.
tapply(): This function is used to apply a function over subset of vectors given by a combination of factors.tapply(vector, factor, function, ...)vector = Created vectorfactor = Created factorfunction = the operation which you want to performExample:# R program to illustrate# tapply() function  # Creating a factorId = c(1, 1, 1, 1, 2, 2, 2, 3, 3)  # Creating a vectorval = c(1, 2, 3, 4, 5, 6, 7, 8, 9)  # applying tapply()result = tapply(val, Id, sum)print(result)Output:1  2  3 
10 18 17 
How does the above code work?
tapply(vector, factor, function, ...)
vector = Created vectorfactor = Created factorfunction = the operation which you want to perform
Example:
# R program to illustrate# tapply() function  # Creating a factorId = c(1, 1, 1, 1, 2, 2, 2, 3, 3)  # Creating a vectorval = c(1, 2, 3, 4, 5, 6, 7, 8, 9)  # applying tapply()result = tapply(val, Id, sum)print(result)
Output:
1  2  3 
10 18 17 

How does the above code work?
mapply(): It’s a multivariate version of lapply(). This function can be applied over several list simultaneously.mapply(function, list1, list2, ...)function = the operation which you want to performlist1, list2 = Created listsExample:# R program to illustrate# mapply() function  # Creating a listA = list(c(1, 2, 3, 4))  # Creating another listB = list(c(2, 5, 1, 6))  # Applying mapply()result = mapply(sum, A, B)print(result)Output:[1] 24

mapply(function, list1, list2, ...)
function = the operation which you want to perform
list1, list2 = Created lists
Example:
# R program to illustrate# mapply() function  # Creating a listA = list(c(1, 2, 3, 4))  # Creating another listB = list(c(2, 5, 1, 6))  # Applying mapply()result = mapply(sum, A, B)print(result)
Output:
[1] 24

anupama0699
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Arrow operator -> in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Top 10 Programming Languages to Learn in 2022
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method