1. 频数统计
对数据进行频数统计,需要有因子类型的数据才行,所谓因子就是可以将数据划分为不同的等级,划分为不同的组别。
f_cyl<- as.factor(mtcars$cyl)#将mtcars中的cyl列作为因子
split(mtcars,f_cyl)#按因子f_cyl的不同水平将数据划分

如果不是因子类型数据,可以使用cut函数进行划分
cut(mtcars$mpg,c(seq(10,50,10)))#将10到50每十个数切一刀分为四组,并且将mpg列数据统计到对应的区间
1.1 一维频数统计
1.1.1 用table函数
table(f_cyl)#对cyl因子进行频数统计
table(cut(mtcars$mpg,c(seq(10,50,10))))#对mpg列数值处于哪个区间进行频数统计

1.2 二维频数统计
1.2.1 用table函数
library(vcd)
library(grid)#载入两个包以使用Arthritis数据集
table(Arthritis$Treatment,Arthritis$Improved)#对这两列进行频数统计
#with(data=Arthritis,(table(Treatment,Improved)))#方法二,意义一致

1.2.2 用xtabs函数
xtabs(formula=~Treatment+Improved,data=Arthritis)

1.2.3 用margin.table()函数
x<-xtabs(~Treatment+Improved,data=Arthritis)#
margin.table(x)#统计总的频数
margin.table(x,1)#统计每行的频数之和,1表示行
margin.table(x,2)#统计每列的频数之和,2表示列

♥1.2.4 用addmargins()函数
这一种数据呈现形式是我最能接受的,推荐使用
x<-xtabs(~Treatment+Improved,data=Arthritis)#
addmargins(x)#统计总的频数
addmargins(x,1)#统计每行的频数之和,1表示行
addmargins(x,2)#统计每列的频数之和,2表示列

1.3 三维频数统计
1.3.1 xtabs函数
这种形式符合逻辑想象,但是肉眼表达不直观
y<-xtabs(~Treatment+Improved+Sex,data=Arthritis)#三维列联表
y

我们可以使用ftable函数使结果表达的更直观,但是弊端是不便于理解
y<-xtabs(~Treatment+Improved+Sex,data=Arthritis)#三维列联表
ftable(y)#将三维列联表转换成平铺式的列联表

2. 频率统计
2.1 一维频数统计
2.1.1 用prop.table函数进行频率的计算
prop.table((table(f_cyl)))#对table(f_cyl)出来的结果进行频率计算

2.2 二维频率统计
2.2.1 用prop.table函数进行频率的计算
x<-xtabs(~Treatment+Improved,data=Arthritis)
prop.table(x)#统计总的频率,具体的含义我忘记了是什么
prop.table(x,1)#按行统计频率,1表示行
prop.table(x,2)#按列统计频率,2表示列

网友评论