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)

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

Similar to A brief introduction to apply functions (20)

Apply Type functions in R.ppt ppt made by me
Apply Type functions in R.ppt ppt made by meApply Type functions in R.ppt ppt made by me
Apply Type functions in R.ppt ppt made by me
aroradoll210
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
AnishaJ7
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
BilawalBaloch1
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Programming in R
Programming in RProgramming in R
Programming in R
Smruti Sarangi
 
Morel, a data-parallel programming language
Morel, a data-parallel programming languageMorel, a data-parallel programming language
Morel, a data-parallel programming language
Julian Hyde
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
statistical computation using R- an intro..
statistical computation using R- an intro..statistical computation using R- an intro..
statistical computation using R- an intro..
Kamarudheen KV
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
R programming
R programmingR programming
R programming
Pramodkumar Jha
 
Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functions
Vivek Singh
 
R교육1
R교육1R교육1
R교육1
Kangwook Lee
 
Rcommands-for those who interested in R.
Rcommands-for those who interested in R.Rcommands-for those who interested in R.
Rcommands-for those who interested in R.
Dr. Volkan OBAN
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
vikram mahendra
 
R Basics
R BasicsR Basics
R Basics
Dr.E.N.Sathishkumar
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
Timothy McBush Hiele
 
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
hanniaarias53
 
Apply Type functions in R.ppt ppt made by me
Apply Type functions in R.ppt ppt made by meApply Type functions in R.ppt ppt made by me
Apply Type functions in R.ppt ppt made by me
aroradoll210
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
AnishaJ7
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
BilawalBaloch1
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
Morel, a data-parallel programming language
Morel, a data-parallel programming languageMorel, a data-parallel programming language
Morel, a data-parallel programming language
Julian Hyde
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
statistical computation using R- an intro..
statistical computation using R- an intro..statistical computation using R- an intro..
statistical computation using R- an intro..
Kamarudheen KV
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functions
Vivek Singh
 
Rcommands-for those who interested in R.
Rcommands-for those who interested in R.Rcommands-for those who interested in R.
Rcommands-for those who interested in R.
Dr. Volkan OBAN
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
vikram mahendra
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
Timothy McBush Hiele
 
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
hanniaarias53
 

Recently uploaded (20)

Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 

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)
  翻译: