In R, iteration is not preferred because it’s computationally expensive.
Apart from the basic looping functions like for and while, R also supports the following vectorized looping functions:
apply()lapply()tapply()sapply()by()The primary goal of these functions is to avoid using loop structures explicitly. They can apply a function on an input list, matrix, or array. These functions accept any function as a parameter.
We’ll be looking into three main functions in detail in this shot.
apply() functionThe apply() function accepts a data frame, vector, list, or array as input and returns a data frame, vector, list, or array as output.
apply(X, MARGIN, FUN)
X: This is a data frame, vector, list, or array.MARGIN: This takes a value or range between 1 and 2 to define where to apply the function, e.g.:
MARGIN=1: The manipulation is performed on rows.MARGIN=2: The manipulation is performed on columns.MARGIN=c(1,2) The manipulation is performed on rows and columns.FUN: This specifies which function should be used. Mean, median, sum, min, max, and other built-in functions, as well as user-defined functions, can be used.Let’s look at the following example.
df <- data.frame(x = 1:4, y = 5:8, z = 10:13)#df x y z# 1 5 10 = 16 (sum by row)# 2 6 11 = 19 (sum by row)# 3 7 12 = 22 (sum by row)# 4 8 13 = 25 (sum by row)# Sum by rowapply(X = df, MARGIN = 1, FUN = sum)
df.lapply() functionThe lapply() function can be used to perform operations on a list or vector that returns a list or vector of the same length as the original with the resultant elements obtained after applying the specified FUN.
lapply(X, FUN)
X: This is a list or vector.FUN: This is the function to be applied on each element of X.Let’s look at the following example.
movies <- c("SPYDERMAN","BATMAN","VERTIGO","CHINATOWN")movies_lower <- lapply(movies, tolower)str(movies_lower)
movies.tolower function and stores the results to movies_lower.movies_lower.sapply() functionThe sapply() function accepts a vector, list, or array as input and returns a vector, list, or array as output.
sapply(X, FUN)
X: This is a vector, list, or array.FUN: This is a function applied to each element of X.Let’s look at the following example.
data <- list(item1 = 1:5,item2 = seq(4,36,8),item4 = c(1,3,5,7,9))# $item1# [1] 1 2 3 4 5 = 15 (summed)# $item2# [1] 4 12 20 28 36 = 100 (summed)# $item4# [1] 1 3 5 7 9 = 25 (summed)sapply(data, sum)
data.data as shown in lines 5-10.Free Resources