通常情况下,你可能想在R中打印一个表格到控制台,以总结一些数据集中的数值。
下面的例子展示了如何通过使用table()和as.table()函数在R中打印表格。
例1:从数据中打印单程表
假设我们在R中拥有以下数据框:
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
position=c('Guard', 'Guard', 'Forward', 'Guard', 'Forward',
'Forward', 'Guard', 'Guard', 'Forward'),
points=c(14, 12, 15, 20, 22, 36, 10, 16, 19))
#view data frame
df
team position points
1 A Guard 14
2 A Guard 12
3 A Forward 15
4 B Guard 20
5 B Forward 22
6 B Forward 36
7 C Guard 10
8 C Guard 16
9 C Forward 19
我们可以使用table()函数来总结位置列中每个唯一值的计数:
#create table for 'position' variable
table1 <- table(df$position)
#view table
table1
Forward Guard
4 5
从表中我们可以看到,'Forward'在位置列中出现了4次,'Guard'出现了5次。
这被称为单程表,因为它总结了一个变量。
例2:从数据中打印双向表
再一次假设我们在R中拥有以下数据框架。
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
position=c('Guard', 'Guard', 'Forward', 'Guard', 'Forward',
'Forward', 'Guard', 'Guard', 'Forward'),
points=c(14, 12, 15, 20, 22, 36, 10, 16, 19))
#view data frame
df
team position points
1 A Guard 14
2 A Guard 12
3 A Forward 15
4 B Guard 20
5 B Forward 22
6 B Forward 36
7 C Guard 10
8 C Guard 16
9 C Forward 19
我们可以使用table()函数来总结球队和位置列中每个唯一值的计数。
#create two-way table for 'team' and 'position' variables
table2 <- table(df$team, df$position)
#view table
table2
Forward Guard
A 1 2
B 2 1
C 1 2
从表中我们可以看到。
- A队有1名前锋
- A队有2名后卫
- B队有2名前锋
以此类推:
这被称为双向表,因为它概括了两个变量的数量。
例3:从头开始打印表格
假设我们已经知道要填入表中的数值。
例如,假设我们想在R中创建以下表格,该表格显示了一项调查的结果,即询问100个人最喜欢哪种运动。

我们可以使用R中的**as.table()**函数来快速创建这个表。
#create matrix
data <- matrix(c(13, 23, 15, 16, 20, 13), ncol=3)
#specify row and column names of matrix
rownames(data) <- c('Male', 'Female')
colnames(data) <- c('Baseball', 'Basketball', 'Football')
#convert matrix to table
data <- as.table(data)
#display table
data
Baseball Basketball Football
Male 13 15 20
Female 23 16 13
表中的数值与我们之前看到的表格中的数值一致。
其他资源
下面的教程解释了如何在R中执行其他常见任务: