By default, the table() function in R creates a table of frequency values but does not include the frequency of NA values.
However, you can use the following methods to create a table and include NA values:
Method 1: Create Table and Always Display Number of NA Values
table(df$my_column, useNA = "always")
Method 2: Create Table and Only Display Number of NA Values if there are Some
table(df$my_column, useNA = "ifany")
The following examples show how to use each method in practice.
Example 1: Create Table and Always Display Number of NA Values
Suppose we have the following data frame in R that contains information about various basketball players:
#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
points=c(20, 25, 14, 18, 19, 12, 12, 15))
#view data frame
df
team points
1 A 20
2 A 25
3 A 14
4 A 18
5 B 19
6 B 12
7 B 12
8 B 15
We can use the following syntax to create a table for the frequency of values in the team column and display the number of NA values whether or not any exist:
#create frequency table of values in team column, including NA values
table(df$team, useNA = "always")
A B
4 4 0
Notice that the resulting table shows that there are 0 NA values in the team column of the data frame.
Since we used the argument useNA = “always”, the table still displayed the number of NA values even though there weren’t any.
Example 2: Create Table and Only Display Number of NA Values if there are Some
Once again suppose we have the following data frame in R that contains information about various basketball players:
#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
points=c(20, 25, 14, 18, 19, 12, 12, 15))
#view data frame
df
team points
1 A 20
2 A 25
3 A 14
4 A 18
5 B 19
6 B 12
7 B 12
8 B 15
We can use the following syntax to create a table for the frequency of values in the team column and only display the number of NA values if any exist:
#create frequency table of values in team column, including NA values if any exist
table(df$team, useNA = "ifany")
A B
4 4
Notice that the resulting table shows the frequency for the values “A” and “B” in the team column, but does not show the frequency of NA values since there aren’t any.
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Create a Two Way Table in R
How to Convert Table to Matrix in R
How to Convert Table to Data Frame in R