Home » How to Use xtabs() in R to Calculate Frequencies

How to Use xtabs() in R to Calculate Frequencies

by Tutor Aspire

The xtabs() function in R allows you to quickly calculate frequencies for one or more variables.

It uses the following basic syntax:

xtabs(~variable_name, data=data)

where:

  • variable_name: The variable that you’d like to calculate the frequencies for.
  • data: The name of the data frame that the variable comes from.

This tutorial shows several examples of how to use this function in practice.

Example 1: Use xtabs() for One-Way Frequencies

The following code shows how to use xtabs() to calculate the frequencies for the variable team:

#create data frame
df rep(c('A', 'B', 'C'), times=c(27, 33, 40)),
                 position=rep(c('Guard', 'Forward', 'Center'), times=c(20, 50, 30)),
                 points=runif(100, 1, 50))

#view first six rows of data frame
head(df)

  team position   points
1    A    Guard 14.00992
2    A    Guard 19.23407
3    A    Guard 29.06981
4    A    Guard 45.50218
5    A    Guard 10.88241
6    A    Guard 45.02109

#calculate frequencies of team variable
xtabs(~team, data=df)

team
 A  B  C 
27 33 40 

From the output we can see that:

  • Team A occurs 27 times in the data frame.
  • Team A occurs 33  times in the data frame.
  • Team A occurs 40 times in the data frame.

Example 2: Use xtabs() for Two-Way Frequencies

The following code shows how to use xtabs() to calculate the two-way frequencies for the variables team and position:

#create data frame
df rep(c('A', 'B', 'C'), times=c(27, 33, 40)),
                 position=rep(c('Guard', 'Forward', 'Center'), times=c(20, 50, 30)),
                 points=runif(100, 1, 50))

#calculate frequencies of team and position variables
xtabs(~team+position, data=df)

    position
team Center Forward Guard
   A      0       7    20
   B      0      33     0
   C     30      10     0 

From the output we can see that:

  • There are 0 Centers on team A.
  • There are 7 Forwards on team A.
  • There are 20 Guards on team A.

And so on.

Using xtabs() for n-Way Frequencies

The xtabs() function can actually be used to calculate frequencies for any number of variables by simply using the following syntax:

xtabs(~variable1+variable2+variable3+...+variablen, data=df)

In practice, this function is used most often to calculate one-way and two-way frequencies.

Additional Resources

How to Calculate Relative Frequencies Using dplyr
How to Perform a COUNTIF Function in R
How to Calculate Cumulative Sums in R

You may also like