Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R table() Function - Frequency Counting

R table() Function - Frequency Counting

R Language Examples R Language Examples

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:

Example

Count the frequency of each category

colors

<-

c

(

"Red"

,

"Blue"

,

"Red"

,

"Green"

,

"Blue"

,

"Red"

,

"Blue"

,

"Green"

,

"Red"

,

"Red"

)

freq

<-

table

(

colors

)

print

(

"Color frequency:"

)

print

(

freq

)

Ratio

prop

<-

prop.table

(

freq

)

print

(

"Color proportion:"

)

print

(

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

)

print

(

"Gender x Purchase cross table:"

)

print

(

cross_table

)

Row percentages

print

(

"Row percentages:"

)

print

(

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 R Language Examples