我使用ftable制作这样的表:
HPV-16 negative positive
Sex HPV-55
female negative 2341 4
positive 11 0
male negative 2140 23
positive 25 2
这是Dput代码。
structure(c(2341L, 11L, 2140L, 25L, 4L, 0L, 23L, 2L), .Dim = c(4L,
2L), class = "ftable", row.vars = list(Sex = c("female", "male"
), `HPV-55` = c("negative", "positive")), col.vars = list(`HPV-16` = c("negative",
"positive")))
和原始数据的样本数据:
structure(list(sex = structure(c(2L, 2L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("female",
"male"), class = c("labelled", "factor"), label = "sex"), orxh16 = structure(c(1L,
1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("negative", "positive"), class = c("labelled",
"factor"), label = "hpv16"), orxh55 = structure(c(1L, 1L, 1L,
NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), .Label = c("negative", "positive"), class = c("labelled",
"factor"), label = "hpv55")), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
我尝试了addmargins:,addmargins(tab1, FUN = list(Total=sum), quiet = T)
但是详细信息(例如行名和布局)将丢失。
Total
2341 4 2345
11 0 11
2140 23 2163
25 2 27
Total 4517 29 4546
我想知道是否有一种方法可以添加列和行的总数,同时让表格的布局看起来像以前一样(如下所示)?谢谢!
HPV-16 negative positive Total
Sex HPV-55
female negative 2341 4 2345
positive 11 0 11
male negative 2140 23 2163
positive 25 2 27
Total 4517 29 4546
addmargins
应该在之前使用ftable
。
xtab1 <- xtabs(~ sex + orxh55 + orxh16, df)
ftable(addmargins(xtab1, margin = 2:3, list(Total = sum)))
# Margins computed over dimensions
# in the following order:
# 1: orxh55
# 2: orxh16
# orxh16 negative positive Total
# sex orxh55
# female negative 10 0 10
# positive 0 0 0
# Total 10 0 10
# male negative 9 0 9
# positive 0 0 0
# Total 9 0 9
样本数据
df <- structure(list(sex = structure(c(2L, 2L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("female",
"male"), class = c("labelled", "factor"), label = "sex"), orxh16 = structure(c(1L,
1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("negative", "positive"), class = c("labelled",
"factor"), label = "hpv16"), orxh55 = structure(c(1L, 1L, 1L,
NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), .Label = c("negative", "positive"), class = c("labelled",
"factor"), label = "hpv55")), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句