📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Common Functions Used with Factors

In addition to factors, we have another function in the apply family called tapply(). We will explore this function along with two other functions that are often used with factors: split() and by().

  • tapply() function:

The tapply() function applies a function to subsets of a vector, grouped by a factor.

Syntax:

tapply(x, f, g)

where,

  • x as a vector,
  • f as a factor, and
  • g as a function.

Example 1:

> # vector
> ages <- c(21, 22, 24, 41, 36, 25)

> # factor
> gen_factor <- factor(c("Male", "Female", "Male", "Male", "Female", "Male"))

> # tapply()
> tapply(ages, gen_factor, mean)
Female   Male 
 29.00  27.75 

Example 2:

> # vector
> salary <- c(50000, 55000, 48000, 60000, 65000, 70000)

> # factor
> department <- factor(c("HR", "IT", "HR", "IT", "Finance", "Finance"))

> # tapply()
> tapply(salary, department, mean)
Finance      HR      IT 
  67500   49000   57500 

  • split() function:

The split() function divides a vector or dataset into groups based on a factor.

Syntax:

split(x, f)

where,

  • x as a vector or data frame,
  • f as a factor

Example 1:

> # split()
> split(ages, gen_factor)
$Female
[1] 22 36

$Male
[1] 21 24 41 25

Note: Each gender gets a separate list.

Example 2:

> # split()
> split(salary, department)
$Finance
[1] 65000 70000

$HR
[1] 50000 48000

$IT
[1] 55000 60000

Note: Each department gets a separate list.

  • by() function:

The by() function is useful when working with data frames, applying functions to subsets.

Syntax:

by(x, f, g)

where,

  • x as data frame or matrix,
  • f as a factor, and
  • g as a function

Example:

> # creating Data Frame
> Name <- c("Madhu", "Mohan", "Madhan", "Murali", "Mahesh", "Manoj")
> Salary <- c(50000, 55000, 48000, 60000, 65000, 70000)
> Department <- c("HR", "IT", "HR", "IT", "Finance", "Finance")
> emp_df <- data.frame(Name, Salary, Department)
> print(emp_df)
    Name Salary Department
1  Madhu  50000         HR
2  Mohan  55000         IT
3 Madhan  48000         HR
4 Murali  60000         IT
5 Mahesh  65000    Finance
6  Manoj  70000    Finance

> # by() function
> result <- by(emp_df$Salary, emp_df$Department, mean)
> print(result)
emp_df$Department: Finance
[1] 67500
---------------------------------------
emp_df$Department: HR
[1] 49000
---------------------------------------
emp_df$Department: IT
[1] 57500
FunctionPurpose
tapply()Applies a function to subsets of a vector, grouped by a factor.
split()Divides a dataset into subsets based on a factor.
by()Applies a function to a data frame by groups.