R语言统计入门第四章描述性统计和图形——4.5表格

library(ISwR)
attach(juul)

4.5表格

4.5.1生成表格


caff.marital<-matrix(c(625,1537,598,242,36,46,38,21,218,327,106,67),nrow = 3,byrow = T)#生成表格,需要一个作为单独向量的表格值的变量
caff.marital

[,1] [,2] [,3] [,4]
[1,] 625 1537 598 242
[2,] 36 46 38 21
[3,] 218 327 106 67

colnames(caff.marital)<-c("0","1-150","151-300",">300")#表格列名称命名
rownames(caff.marital)<-c("Married","Prev.married","Single")#行名称命名
caff.marital

0 1-150 151-300 >300
Married 625 1537 598 242
Prev.married 36 46 38 21
Single 218 327 106 67

names(dimnames(caff.marital))<-c("marital","consution")#添加变量名
caff.marital

consution
marital 0 1-150 151-300 >300
Married 625 1537 598 242
Prev.married 36 46 38 21
Single 218 327 106 67

as.data.frame(as.table(caff.marital))#把表格转换为计数的数据框

marital consution Freq
1 Married 0 625
2 Prev.married 0 36
3 Single 0 218
4 Married 1-150 1537
5 Prev.married 1-150 46
6 Single 1-150 327
7 Married 151-300 598
8 Prev.married 151-300 38
9 Single 151-300 106
10 Married >300 242
11 Prev.married >300 21
12 Single >300 67

table(sex)#生成sex变量的表格

sex
M F
621 713

table(sex,menarche)#生成sex与menarche的二维变量表

menarche
sex No Yes
M 0 0
F 369 335

table(menarche,tanner)#同上

tanner
menarche I II III IV V
No 221 43 32 14 2
Yes 1 1 5 26 202

xtabs(~tanner+sex,data=juul)#将juul数据框下的sex和tanner分类变量制表,注意模型公式接口

sex
tanner M F
I 291 224
II 55 48
III 34 38
IV 41 40
V 124 204

xtabs(~dgn+diab+coma,data=stroke)#多向表格的生成,

, , coma = No

diab
dgn No Yes
ICH 53 6
ID 143 21
INF 411 64
SAH 38 0

, , coma = Yes

diab
dgn No Yes
ICH 19 1
ID 23 3
INF 23 2
SAH 9 0

ftable(coma+diab~dgn,data=stroke)#生成扁平的表格,左边参数为整页制表,右边参数为向下制表

coma No Yes
diab No Yes No Yes
dgn
ICH 53 6 19 1
ID 143 21 23 3
INF 411 64 23 2
SAH 38 0 9 0

t(caff.marital)#对表格进行转置

marital
consution Married Prev.married Single
0 625 36 218
1-150 1537 46 327
151-300 598 38 106

300 242 21 67

#4.5.2边际表格和相对频数
tanner.sex<-table(tanner,sex)#生成sex与tanner的二维变量表保存到tanner.sex
tanner.sex

sex
tanner M F
I 291 224
II 55 48
III 34 38
IV 41 40
V 124 204

margin.table(tanner.sex,1)#计算边际表格,参数1,2分别是给出行、列的总数

tanner
I II III IV V
515 103 72 81 328

margin.table(tanner.sex,2)

sex
M F
545 554

prop.table(tanner.sex,1)#相对频数表,参数1,2表示行、列和为1

sex
tanner M F
I 0.5650485 0.4349515
II 0.5339806 0.4660194
III 0.4722222 0.5277778
IV 0.5061728 0.4938272
V 0.3780488 0.6219512

tanner.sex/sum(tanner.sex)#相对于表格总和的比例

sex
tanner M F
I 0.26478617 0.20382166
II 0.05004550 0.04367607
III 0.03093722 0.03457689
IV 0.03730664 0.03639672
V 0.11282985 0.18562329

猜你喜欢

转载自blog.csdn.net/qq_38742877/article/details/86570550
今日推荐