R table() Function - Frequency Counting
The R table() function is used to count the frequency of each value in a vector, generating a frequency table.
table() can also count cross frequencies of multiple categorical variables (contingency tables), a fundamental tool for data analysis.
The syntax of the table() function is as follows:
table(x, y = NULL)
Parameter Description:
-
x A categorical variable or vector.
-
y Optional, a second categorical variable, used to generate a cross table.
Example
Count the frequency of each category
colors
<-
c
(
"Red"
,
"Blue"
,
"Red"
,
"Green"
,
"Blue"
,
"Red"
,
"Blue"
,
"Green"
,
"Red"
,
"Red"
)
freq
<-
table
(
colors
)
(
"Color frequency:"
)
(
freq
)
Ratio
prop
<-
prop.table
(
freq
)
(
"Color proportion:"
)
(
prop
)
The output of the code above is:
[1] "颜色频数:"
colors
红 蓝 绿
5 3 2
[1] "颜色比例:"
colors
红 蓝 绿
0.5 0.3 0.2
table() can also generate multi-dimensional cross tables:
Example
Cross table: gender x whether purchased
gender
<-
c
(
"male"
,
"female"
,
"male"
,
"female"
,
"male"
,
"male"
,
"female"
,
"female"
)
purchase
<-
c
(
"Yes"
,
"Yes"
,
"No"
,
"Yes"
,
"Yes"
,
"No"
,
"No"
,
"Yes"
)
cross_table
<-
table
(
gender, purchase
)
(
"Gender x Purchase cross table:"
)
(
cross_table
)
Row percentages
(
"Row percentages:"
)
(
prop.table
(
cross_table, margin
=
1
)
)
The output of the code above is:
[1] "性别 × 购买 交叉表:"
purchase
gender 否 是
男 2 2
女 1 3
[1] "行百分比:"
purchase
gender 否 是
男 0.50 0.50
女 0.25 0.75
R Language Examples