# R 中的 table()函式

Sheeraz Gul 2022年7月18日 R R Function

`table()` 方法用於分類表示資料。本教程演示如何在 R 中使用 `table()` 方法。

## R 中的 `table()` 函式

``````table(x)
``````

``````# create a dataframe
Delftstack <- data.frame(Name=c('Jack', 'John', 'Mike', 'Michelle', 'Jhonny'),
LastName=c('Danials', 'Cena', 'Chandler', 'McCool', 'Nitro'),
Id=c(101, 102, 103, 104, 105),
Designation=c('CEO', 'Project Manager', 'Senior Dev', 'Junior Dev', 'Intern'))

#view data frame
Delftstack

#Create frequency table for LastName column
table(Delftstack\$LastName)
``````

``````      Name LastName  Id     Designation
1     Jack  Danials 101             CEO
2     John     Cena 102 Project Manager
3     Mike Chandler 103      Senior Dev
4 Michelle   McCool 104      Junior Dev
5   Jhonny    Nitro 105          Intern

Cena Chandler  Danials   McCool    Nitro
1        1        1        1        1
``````

``````#calculate frequency table of proportions for LastName Column
prop.table(table(Delftstack\$LastName))
``````

``````    Cena Chandler  Danials   McCool    Nitro
0.2      0.2      0.2      0.2      0.2
``````

``````#Create frequency table for Name and LastName column
table(Delftstack\$Name, Delftstack\$LastName)
``````

``````           Cena Chandler Danials McCool Nitro
Jack        0        0       1      0     0
Jhonny      0        0       0      0     1
John        1        0       0      0     0
Michelle    0        0       0      1     0
Mike        0        1       0      0     0
``````

``````#calculate frequency table of proportions for Name and LastName Column
prop.table(table(Delftstack\$Name, Delftstack\$LastName))
``````

``````           Cena Chandler Danials McCool Nitro
Jack      0.0      0.0     0.2    0.0   0.0
Jhonny    0.0      0.0     0.0    0.0   0.2
John      0.2      0.0     0.0    0.0   0.0
Michelle  0.0      0.0     0.0    0.2   0.0
Mike      0.0      0.2     0.0    0.0   0.0
``````

``````# create a dataframe
Delftstack <- data.frame(Name=c('Jack', 'John', 'Mike', 'Michelle', 'Jhonny'),
LastName=c('Danials', 'Cena', 'Chandler', 'McCool', 'Nitro'),
Id=c(101, 102, 103, 104, 105),
Designation=c('CEO', 'Project Manager', 'Senior Dev', 'Junior Dev', 'Intern'))

#view data frame
Delftstack

#Create frequency table for LastName column
table(Delftstack\$LastName)

#calculate frequency table of proportions for LastName Column
prop.table(table(Delftstack\$LastName))

#Create frequency table for Name and LastName column
table(Delftstack\$Name, Delftstack\$LastName)

#calculate frequency table of proportions for Name and LastName Column
prop.table(table(Delftstack\$Name, Delftstack\$LastName))
``````
Author: Sheeraz Gul

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.