Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

How to use apply, sapply, lapply, tapply functions in R?

Description

To know the apply, sapply, lapply, tapply functions using R programming.

Process

apply:

It can apply over array, matrix or data frame

R Function : apply(x, MARGIN= , FUN= )

x -- array or matrix or data frame MARGIN -- 1 for row, 2 for column

FUN -- functions may be mean,median, mode etc.

lapply:

It can apply over elements of list or data frame

Returns list

It doesn’t need margin value

R Function :lapply(x, FUN= )

x -- list or data frame

FUN -- functions may be mean,median, mode etc.

sapply:

Same as lapply but simplifies the responce Returns vector

R Function :sapply(x, FUN= )

x -- list or data frame

FUN -- functions may be mean,median, mode etc.

tapply:

It Computes measure of mean, median, min, max or a function for each factor R Function : tapply(x,INDEX= ,FUN= )

x -- vector

INDEX -- a list containing factor

FUN -- function applied to each element of x

Sapmle Code

#Functions : apply,lapply,sapply,tapply

 

#Input vector

my_matrix<-matrix(1:10, nrow=2,ncol=5,byrow = TRUE)

my_list<-list(“sangeetha”,”sheela”,”nandhini”,”sweatha”,”divya”)

 

#apply

#mean value of row of input matrix

apply(my_matrix,1,FUN=mean)

 

#mean value of column of input matrix

apply(my_matrix, 2, FUN = mean)

 

#lapply

lapply(my_list,toupper)

 

#sapply

sapply(my_list,toupper)

 

#tapply

input<-iris

tapply(input$Sepal.Length,input$Species,mean)

Screenshots
use apply, sapply, lapply, tapply functions in R
Functions : apply,lapply,sapply,tapply
Input vector