SlideShare a Scribd company logo
A brief introduction to
“apply” in R
By - Niket Chaurasia
Kiams PG2019-21
apply()
The apply() function can be feed with
many functions to perform redundant
application on a collection of object (data
frame, list, vector, etc.).
The purpose of apply() is primarily to
avoid explicit uses of loop constructs.
They can be used for an input list, matrix
or array and apply a function.Any
function can be passed into apply().
apply()
function
We use apply()
over a matrice.
This function
takes 5
arguments:
apply(X, MARGIN, FUN)
 Here:
 -x: an array or matrix
 -MARGIN: take a value or range between 1 and 2 to define where
to apply the function:
 -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 colu
mns
 -FUN: tells which function to apply. Built functions like mean, medi
an, sum, min, max and even user-defined functions can be applied
APPLY()
 # create a matrix of 10 rows x 2 columns
 m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
 # mean of the rows
 apply(m, 1, mean)
 # mean of the columns
 apply(m, 2, mean)
 # divide all values by 2
 apply(m, 1:2, function(x) x/2)
Apply()
 #---------- apply() function ----------
 #case 1. matrix as an input argument
 m1 <- matrix(1:9, nrow =3)
 m1
 result <- apply(m1,1,mean) #mean of elements for each row
 result
 class(result) #class is a vector
 result <- apply(m1,2,sum) #sum of elements for each column
 result
 class(result) #class is a vector
 result <- apply(m1,1,cumsum) #cumulative sum of elements for each row
 result #by default column-wise order
 class(result) #class is a matrix
 matrix(apply(m1,1,cumsum), nrow = 3, byrow = T) #for row-wise order
 #user defined function
 check<-function(x){
 return(x[x>5])
 }
 result <- apply(m1,1,check) #user defined function as an argument
 result
 class(result) #class is a list
apply
 #case 2. data frame as an input
 ratings <- c(4.2, 4.4, 3.4, 3.9, 5, 4.1, 3.2, 3.9, 4.6, 4.8, 5, 4, 4.5, 3.9, 4.7, 3.6)
 employee.mat <- matrix(ratings,byrow=TRUE,nrow=4,dimnames = list(c("Quarter1","Quarter2","Quarter3","Quarter4"),c("Hari","Shri","John","Albert")))
 employee <- as.data.frame(employee.mat)
 employee
 result <- apply(employee,2,sum) #sum of elements for each column
 result
 class(result) #class is a vector
 result <- apply(employee,1,cumsum) #cumulative sum of elements for each row
 result #by default column-wise order
 class(result) #class is a matrix
 #user defined function
 check<-function(x){
 return(x[x>4.2])
 }
 result <- apply(employee,2,check) #user defined function as an argument
 result
 class(result) #class is a list
 ######## Application on Data#####################
 attach(iris)
 head(iris)
 # get the mean of the first 4 variables, by species
 by(iris[, 1:4], Species, colMeans)
lapply()
function
 l in lapply() stands for list.The difference between lapply() and app
ly() lies between the output return.The output of lapply() is a list. l
apply() can be used for other objects like data frames and lists.
 lapply(X, FUN)
 Arguments:
 -X:A vector or an object
 -FUN: Function applied to each element of x
lapply()
 A very easy example can be to change the string value of a matrix
to lower case with tolower function.We construct a matrix with
the name of the famous movies.The name is in upper case format.
 movies <- c("SPYDERMAN","BATMAN","VERTIGO","CHINATOW
N")
 movies_lower <-lapply(movies, tolower)
 str(movies_lower)
 ##### 2. lapply() function###################
 #---------- lapply() function ----------
 #case 1. vector as an input argument
 result <- lapply(ratings,mean)
 result
 class(result) #class is a list
 #case 2. list as an input argument
 list1<-list(maths=c(64,45,89,67),english=c(79,84,62,80),physics=c(68,72,69,80),chemistry = c(99,91,84,89))
 list1
 result <- lapply(list1,mean)
 result
 class(result) #class is a list
 #user defined function
 check<-function(x){
 return(x[x>75])
 }
 result <- lapply(list1,check) #user defined function as an argument
 result
 class(result) #class is a list
 #case 3. dataframe as an input argument
 result <- lapply(employee,sum) #sum of elements for each column
 result
 class(result) #class is a list
 result <- lapply(employee,cumsum) #cumulative sum of
elements for each row
 result
 class(result) #class is a list
 #user defined function
 check<-function(x){
 return(x[x>4.2])
 }
 result <- lapply(employee,check) #user defined function as
an argument
 result
 class(result) #class is a list
 func12 <- function(x) {
 if (x < 0.25) {
 return (1-4*x)
 }
 if (x < 0.50) {
 return (-1 + 4*x)
 }
 if (x < 0.75) {
 return (3 - 4*x)
 }
 return (-3 + 4*x)
 }
 x <- 0:20/20
 x
 y <- lapply(x, func12)
 y
 X11()
 plot(x, y)
 lines(x,y, col='red')
 locator(1)
sapply() functi
on
sapply() is a simplified form of lapply(). It has one
additional argument simplify with default value as
true, if simplify = F then sapply() returns a list similar
to lapply(),
otherwise, it returns the simplest output form
possible.
sapply
 #case 1. vector as an input argument
result <- sapply(ratings,mean)
result
class(result) #class is a vector
result <- sapply(ratings,mean, simplify = FALSE)
result
class(result) #class is a list
result <- sapply(ratings,range)
result
class(result) #class is a matrix#case 2. list as an input
argument
result <- sapply(list1,mean)
result
class(result) #class is a vector
result <- sapply(list1,range)
result
class(result) #class is a matrix
#user defined function
check<-function(x){
return(x[x>75])
}
result <- sapply(list1,check) #user defined function as an argument
result
class(result) #class is a list#case 3. dataframe as an input argument
result <- sapply(employee,mean)
result
class(result) #class is a vector
result <- sapply(employee,range)
result
class(result) #class is a matrix
#user defined function
check<-function(x){
return(x[x>4])
}
result <- sapply(employee,check) #user defined function as an argument
result
class(result) #class is a list
tapply() functi
on
4. tapply() function
tapply() is helpful while dealing with categorical variables,
it applies a function to numeric data distributed across various
categories.
The simplest form of tapply() can be understood as
tapply(column 1, column 2, FUN)
where column 1 is the numeric column on which function is
applied,
column 2 is a factor object and FUN is for the function to be
performed.
salary <- c(21000,29000,32000,34000,45000)
designation<-c("Programmer","Senior Programmer","Senior Programmer",
"Senior Programmer","Manager")
gender <- c("M","F","F","M","M")
result <- tapply(salary,designation,mean)
result
class(result) #class is an array
result <- tapply(salary,list(designation,gender),mean)
result
class(result) #class is a matrix
by() function
5. by() function
by() does a similar job to tapply() i.e. it applies an operation to numeric vector
values distributed across various categories. by() is a wrapper function of tapply().
#---------- by() function ----------
result <- by(salary,designation,mean)
result
class(result) #class is of "by" type
result[2] #accessing as a vector element
as.list(result) #converting into a list
result <- by(salary,list(designation,gender),mean)
result
class(result) #class is of "by" type
library("gamclass")
data("FARS")
by(FARS[2:4], FARS$airbagAvail, colMeans)
mapply() functi
on
6. mapply() function
The ‘m’ in mapply() refers to ‘multivariate’. It applies the specified functions to
the arguments one by one. Note that here function is specified as the first
argument whereas in other apply functions as the third argument.
#---------- mapply() function ----------
result <- mapply(rep, 1:4, 4:1)
result
class(result) #class is a list
result <- mapply(rep, 1:4, 4:4)
class(result) #class is a matrix
Mapply()
 Description: “mapply is a multivariate version of sapply. mapply
applies FUN to the first elements of each (…) argument, the
second elements, the third elements, and so on.”
 The mapply documentation is full of quite complex examples, but
here’s a simple, silly one:

 l1 <- list(a = c(1:10), b = c(11:20))
 l2 <- list(c = c(21:30), d = c(31:40))
 # sum the corresponding elements of l1 and l2
 mapply(sum, l1$a, l1$b, l2$c, l2$d)

More Related Content

What's hot (20)

PPT
Sql operators & functions 3
Dr. C.V. Suresh Babu
 
PPTX
DataFrame in Python Pandas
Sangita Panchal
 
PDF
INTRODUCTION TO MATLAB session with notes
Infinity Tech Solutions
 
PPTX
Intro to matlab
Norhan Mohamed
 
PDF
MATLAB for Technical Computing
Naveed Rehman
 
PPTX
Introduction to matlab lecture 3 of 4
Randa Elanwar
 
PPTX
Functions
Ankit Dubey
 
PDF
A Generic Explainability Framework for Function Circuits
Sylvain Hallé
 
PPT
Single row functions
Balqees Al.Mubarak
 
PPTX
Introduction to matlab lecture 2 of 4
Randa Elanwar
 
PPTX
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
PPTX
User Defined Functions in MATLAB part 2
Shameer Ahmed Koya
 
PDF
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
PPTX
Mbd2
Mahmoud Hussein
 
PDF
Tutorial2
ashumairitar
 
PPTX
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
PPTX
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
PDF
Hive function-cheat-sheet
Dr. Volkan OBAN
 
PDF
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 
Sql operators & functions 3
Dr. C.V. Suresh Babu
 
DataFrame in Python Pandas
Sangita Panchal
 
INTRODUCTION TO MATLAB session with notes
Infinity Tech Solutions
 
Intro to matlab
Norhan Mohamed
 
MATLAB for Technical Computing
Naveed Rehman
 
Introduction to matlab lecture 3 of 4
Randa Elanwar
 
Functions
Ankit Dubey
 
A Generic Explainability Framework for Function Circuits
Sylvain Hallé
 
Single row functions
Balqees Al.Mubarak
 
Introduction to matlab lecture 2 of 4
Randa Elanwar
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
User Defined Functions in MATLAB part 2
Shameer Ahmed Koya
 
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
Tutorial2
ashumairitar
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
Hive function-cheat-sheet
Dr. Volkan OBAN
 
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 

Similar to A brief introduction to apply functions (20)

PPT
Apply Type functions in R.ppt ppt made by me
aroradoll210
 
PDF
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
PDF
purrr.pdf
Mateus S. Xavier
 
PPTX
Language R
Girish Khanzode
 
PDF
Day 4a iteration and functions.pptx
Adrien Melquiond
 
PPTX
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
PPT
R for Statistical Computing
Mohammed El Rafie Tarabay
 
PDF
R Programming Reference Card
Maurice Dawson
 
PDF
R code for data manipulation
Avjinder (Avi) Kaler
 
PDF
R code for data manipulation
Avjinder (Avi) Kaler
 
PDF
20170509 rand db_lesugent
Prof. Wim Van Criekinge
 
PDF
@ R reference
vickyrolando
 
PDF
R command cheatsheet.pdf
Ngcnh947953
 
PDF
Reference card for R
Dr. Volkan OBAN
 
PDF
Short Reference Card for R users.
Dr. Volkan OBAN
 
PPTX
BA lab1.pptx
sherifsalem24
 
PPTX
data frames.pptx
RacksaviR
 
PPTX
R programming
Pramodkumar Jha
 
PDF
Basic and logical implementation of r language
Md. Mahedi Mahfuj
 
PDF
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
Apply Type functions in R.ppt ppt made by me
aroradoll210
 
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
purrr.pdf
Mateus S. Xavier
 
Language R
Girish Khanzode
 
Day 4a iteration and functions.pptx
Adrien Melquiond
 
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
R for Statistical Computing
Mohammed El Rafie Tarabay
 
R Programming Reference Card
Maurice Dawson
 
R code for data manipulation
Avjinder (Avi) Kaler
 
R code for data manipulation
Avjinder (Avi) Kaler
 
20170509 rand db_lesugent
Prof. Wim Van Criekinge
 
@ R reference
vickyrolando
 
R command cheatsheet.pdf
Ngcnh947953
 
Reference card for R
Dr. Volkan OBAN
 
Short Reference Card for R users.
Dr. Volkan OBAN
 
BA lab1.pptx
sherifsalem24
 
data frames.pptx
RacksaviR
 
R programming
Pramodkumar Jha
 
Basic and logical implementation of r language
Md. Mahedi Mahfuj
 
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
Ad

Recently uploaded (20)

PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Ad

A brief introduction to apply functions

  • 1. A brief introduction to “apply” in R By - Niket Chaurasia Kiams PG2019-21
  • 2. apply() The apply() function can be feed with many functions to perform redundant application on a collection of object (data frame, list, vector, etc.). The purpose of apply() is primarily to avoid explicit uses of loop constructs. They can be used for an input list, matrix or array and apply a function.Any function can be passed into apply().
  • 3. apply() function We use apply() over a matrice. This function takes 5 arguments: apply(X, MARGIN, FUN)  Here:  -x: an array or matrix  -MARGIN: take a value or range between 1 and 2 to define where to apply the function:  -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 colu mns  -FUN: tells which function to apply. Built functions like mean, medi an, sum, min, max and even user-defined functions can be applied
  • 4. APPLY()  # create a matrix of 10 rows x 2 columns  m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)  # mean of the rows  apply(m, 1, mean)  # mean of the columns  apply(m, 2, mean)  # divide all values by 2  apply(m, 1:2, function(x) x/2)
  • 5. Apply()  #---------- apply() function ----------  #case 1. matrix as an input argument  m1 <- matrix(1:9, nrow =3)  m1  result <- apply(m1,1,mean) #mean of elements for each row  result  class(result) #class is a vector  result <- apply(m1,2,sum) #sum of elements for each column  result  class(result) #class is a vector  result <- apply(m1,1,cumsum) #cumulative sum of elements for each row  result #by default column-wise order  class(result) #class is a matrix  matrix(apply(m1,1,cumsum), nrow = 3, byrow = T) #for row-wise order  #user defined function  check<-function(x){  return(x[x>5])  }  result <- apply(m1,1,check) #user defined function as an argument  result  class(result) #class is a list
  • 6. apply  #case 2. data frame as an input  ratings <- c(4.2, 4.4, 3.4, 3.9, 5, 4.1, 3.2, 3.9, 4.6, 4.8, 5, 4, 4.5, 3.9, 4.7, 3.6)  employee.mat <- matrix(ratings,byrow=TRUE,nrow=4,dimnames = list(c("Quarter1","Quarter2","Quarter3","Quarter4"),c("Hari","Shri","John","Albert")))  employee <- as.data.frame(employee.mat)  employee  result <- apply(employee,2,sum) #sum of elements for each column  result  class(result) #class is a vector  result <- apply(employee,1,cumsum) #cumulative sum of elements for each row  result #by default column-wise order  class(result) #class is a matrix  #user defined function  check<-function(x){  return(x[x>4.2])  }  result <- apply(employee,2,check) #user defined function as an argument  result  class(result) #class is a list  ######## Application on Data#####################  attach(iris)  head(iris)  # get the mean of the first 4 variables, by species  by(iris[, 1:4], Species, colMeans)
  • 7. lapply() function  l in lapply() stands for list.The difference between lapply() and app ly() lies between the output return.The output of lapply() is a list. l apply() can be used for other objects like data frames and lists.  lapply(X, FUN)  Arguments:  -X:A vector or an object  -FUN: Function applied to each element of x
  • 8. lapply()  A very easy example can be to change the string value of a matrix to lower case with tolower function.We construct a matrix with the name of the famous movies.The name is in upper case format.  movies <- c("SPYDERMAN","BATMAN","VERTIGO","CHINATOW N")  movies_lower <-lapply(movies, tolower)  str(movies_lower)
  • 9.  ##### 2. lapply() function###################  #---------- lapply() function ----------  #case 1. vector as an input argument  result <- lapply(ratings,mean)  result  class(result) #class is a list  #case 2. list as an input argument  list1<-list(maths=c(64,45,89,67),english=c(79,84,62,80),physics=c(68,72,69,80),chemistry = c(99,91,84,89))  list1  result <- lapply(list1,mean)  result  class(result) #class is a list  #user defined function  check<-function(x){  return(x[x>75])  }  result <- lapply(list1,check) #user defined function as an argument  result  class(result) #class is a list  #case 3. dataframe as an input argument  result <- lapply(employee,sum) #sum of elements for each column  result  class(result) #class is a list
  • 10.  result <- lapply(employee,cumsum) #cumulative sum of elements for each row  result  class(result) #class is a list  #user defined function  check<-function(x){  return(x[x>4.2])  }  result <- lapply(employee,check) #user defined function as an argument  result  class(result) #class is a list  func12 <- function(x) {  if (x < 0.25) {  return (1-4*x)  }  if (x < 0.50) {  return (-1 + 4*x)  }  if (x < 0.75) {  return (3 - 4*x)  }  return (-3 + 4*x)  }  x <- 0:20/20  x  y <- lapply(x, func12)  y  X11()  plot(x, y)  lines(x,y, col='red')  locator(1)
  • 11. sapply() functi on sapply() is a simplified form of lapply(). It has one additional argument simplify with default value as true, if simplify = F then sapply() returns a list similar to lapply(), otherwise, it returns the simplest output form possible.
  • 12. sapply  #case 1. vector as an input argument result <- sapply(ratings,mean) result class(result) #class is a vector result <- sapply(ratings,mean, simplify = FALSE) result class(result) #class is a list result <- sapply(ratings,range) result class(result) #class is a matrix#case 2. list as an input argument result <- sapply(list1,mean) result class(result) #class is a vector result <- sapply(list1,range) result class(result) #class is a matrix
  • 13. #user defined function check<-function(x){ return(x[x>75]) } result <- sapply(list1,check) #user defined function as an argument result class(result) #class is a list#case 3. dataframe as an input argument result <- sapply(employee,mean) result class(result) #class is a vector result <- sapply(employee,range) result class(result) #class is a matrix #user defined function check<-function(x){ return(x[x>4]) } result <- sapply(employee,check) #user defined function as an argument result class(result) #class is a list
  • 14. tapply() functi on 4. tapply() function tapply() is helpful while dealing with categorical variables, it applies a function to numeric data distributed across various categories. The simplest form of tapply() can be understood as tapply(column 1, column 2, FUN) where column 1 is the numeric column on which function is applied, column 2 is a factor object and FUN is for the function to be performed.
  • 15. salary <- c(21000,29000,32000,34000,45000) designation<-c("Programmer","Senior Programmer","Senior Programmer", "Senior Programmer","Manager") gender <- c("M","F","F","M","M") result <- tapply(salary,designation,mean) result class(result) #class is an array result <- tapply(salary,list(designation,gender),mean) result class(result) #class is a matrix
  • 16. by() function 5. by() function by() does a similar job to tapply() i.e. it applies an operation to numeric vector values distributed across various categories. by() is a wrapper function of tapply(). #---------- by() function ---------- result <- by(salary,designation,mean) result class(result) #class is of "by" type result[2] #accessing as a vector element as.list(result) #converting into a list result <- by(salary,list(designation,gender),mean) result class(result) #class is of "by" type library("gamclass") data("FARS") by(FARS[2:4], FARS$airbagAvail, colMeans)
  • 17. mapply() functi on 6. mapply() function The ‘m’ in mapply() refers to ‘multivariate’. It applies the specified functions to the arguments one by one. Note that here function is specified as the first argument whereas in other apply functions as the third argument. #---------- mapply() function ---------- result <- mapply(rep, 1:4, 4:1) result class(result) #class is a list result <- mapply(rep, 1:4, 4:4) class(result) #class is a matrix
  • 18. Mapply()  Description: “mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each (…) argument, the second elements, the third elements, and so on.”  The mapply documentation is full of quite complex examples, but here’s a simple, silly one:   l1 <- list(a = c(1:10), b = c(11:20))  l2 <- list(c = c(21:30), d = c(31:40))  # sum the corresponding elements of l1 and l2  mapply(sum, l1$a, l1$b, l2$c, l2$d)