*13*

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 ofteamvariable 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 ofteamandpositionvariables 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