apply lapply tapply sapply Function in R

2019-08-19 Rahul Swami Download Code

This instructional exercise points at presenting the apply( ) work collection. The apply( ) function is the foremost basic of all collection. We are going too learn lapply( ), tapply( ), and sapply( ). The apply collection can be seen as a substitute to the loop.

apply() function

R language has a more efficient to perform iterations with the help of Apply functions.

We use apply() over a matrice.

 

apply(A, MARGIN, FUN)

A - an array
MARGIN - range between numbers MARGIN=1 - performed on rows MARGIN=2 - performed on columns MARGIN=c(1,2) - performed on rows and columns FUN - apply function.
n1 <- matrix(C<-(1:10),nrow=5, ncol=6)
n1
m1 <- apply(n1, 2, sum)
m1

Output :

lapply() function

lapply( )- l stands for list. The difference between lapply() and apply() is the output of lapply() is a list and lapply() can be used like data frames and lists.

this function does not need margin.

lapply (A, FUN)

movie <- c("ANTMAN","SUPERMAN","AVENGER","SPIDERMAN")
movies_lower <-lapply(movie, tolower)
str(movies_lower)

Output:

sapply() function

This function return a vector not list.

sapply(A, FUN)

dt <- cars
l_cars <- lapply(dt, min)
s_cars <- sapply(dt, min)
l_cars

Output:

tapply() function

the function computes a measure like mean, median, max, min etc.
tapply(A, INDEX, FUN = NULL)
data(iris)
tapply(iris$Sepal.Width, iris$Species, median)


Output:




About author

Card image cap
Rahul Swami

Experienced in providing key insights with advanced statistical methods, data modeling, and graphical display, utilizing the software that best suits your needs, with advanced skill in R.!

-R Developer

0 Comments