我正在创建一个包含2个因子的交叉表,其中包含另一个变量
的总和b<-xtabs(utib~qpl+i , data=data )
这给我一张像
这样的表格 <=2.5 2.5-5 5-10 10-50 50-150 150-250 >250 NA
aaaa 3231 211 64 10 1 0 0 32
bbbbbbbbb 442 78 7 3 0 0 0 5
cccccc 6462 466 76 6 0 0 0 157
我需要在最后一行添加每列的总和 我需要它保持'table class',因为那时我必须用代码导出它:
library(PerformanceAnalytics))
win.metafile(file)
PerformanceAnalytics:::textplot(c)
dev.off()
答案 0 :(得分:2)
您可以使用addmargin()
功能
#sample data
data<-data.frame(
utib=rpois(50,10),
qpl=sample(letters[1:3], 50, replace=T),
i=cut(runif(50,0,250), breaks=c(0,2.5,5,10,50,150))
)
(b<-xtabs(utib~qpl+i , data=data ) )
# i
# qpl (0,2.5] (2.5,5] (5,10] (10,50] (50,150]
# a 0 12 24 46 53
# b 0 0 0 0 100
# c 0 0 0 46 42
(bb<-addmargins(b, margin=1))
# i
# qpl (0,2.5] (2.5,5] (5,10] (10,50] (50,150]
# a 0 12 24 46 53
# b 0 0 0 0 100
# c 0 0 0 46 42
# Sum 0 12 24 92 195
答案 1 :(得分:0)
使用Flick先生的数据框,这是一种dcast
和边距参数的方法:
(b <- dcast(data, utib~qpl+i, fun.aggregate = length, margins = TRUE))
Using i as value column: use value.var to override.
utib a_(50,150] a_NA a_(all) b_(10,50] b_(50,150] b_NA b_(all) c_(10,50] c_(50,150] c_NA c_(all) (all)_(all)
1 4 1 0 1 0 0 1 1 0 1 0 1 3
2 5 0 0 0 0 1 0 1 0 1 0 1 2
3 6 1 0 1 1 0 1 2 0 1 0 1 4
4 7 0 2 2 0 1 0 1 0 0 1 1 4
5 8 2 1 3 0 1 0 1 0 1 1 2 6
6 9 2 1 3 1 0 2 3 0 0 2 2 8
7 10 3 0 3 0 2 0 2 0 0 0 0 5
8 11 1 1 2 0 1 0 1 0 0 1 1 4
9 12 1 1 2 0 0 0 0 1 0 0 1 3
10 13 1 1 2 1 0 0 1 0 0 0 0 3
11 14 0 0 0 1 0 0 1 0 0 0 0 1
12 15 0 1 1 0 0 0 0 0 0 1 1 2
13 16 1 0 1 0 0 0 0 0 0 0 0 1
14 17 0 0 0 0 1 0 1 0 0 1 1 2
15 19 0 1 1 0 0 0 0 0 0 0 0 1
16 20 0 0 0 0 0 1 1 0 0 0 0 1
17 (all) 13 9 22 4 7 5 16 1 4 7 12 50