tapply() function

The tapply() helps us to compute statistical measures (mean, median, min, max, etc..) or a self-written function operation for each factor variable in a vector. It helps us to create a subset of a vector and then apply some functions to each of the subsets. For example, in an organization, if we have data of salary of employees and we want to find the mean salary for male and female, then we can use tapply() function with male and female as factor variable gender.

Syntax: tapply( x, index,  fun )

Parameters:

  • x: determines the input vector or an object.
  • index: determines the factor vector that helps us distinguish the data.
  • fun: determines the function that is to be applied to input data.

Example:

Here, is a basic example showcasing the use of the tapply() function on the diamonds dataset which is provided by the tidyverse package library.

R




# load library tidyverse
library(tidyverse)
  
# print head of diamonds dataset
print(" Head of data:")
head(diamonds)
  
# apply tapply function to get average price by cut
print("Average price for each cut of diamond:")
tapply(diamonds$price, diamonds$cut, mean)


Output:



apply(), lapply(), sapply(), and tapply() in R

In this article, we will learn about the apply(), lapply(), sapply(), and tapply() functions in the R Programming Language.

The apply() collection is a part of R essential package. This family of functions helps us to apply a certain function to a certain data frame, list, or vector and return the result as a list or vector depending on the function we use. There are these following four types of function in apply() function family:

Similar Reads

apply() function

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained....

lapply() function

...

sapply() function

The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object. Since the lapply() function applies a certain operation to all the elements of the list it doesn’t need a MARGIN....

tapply() function

...

Contact Us