gpt4 book ai didi

r - 在ftable中添加列和行总计

转载 作者:行者123 更新时间:2023-12-04 10:36:34 27 4
gpt4 key购买 nike

我使用 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

最佳答案

刚刚找到一种方法,使用 summarytool::ctable。虽然表格由分组变量分隔,但它可以提供与 ftable 中类似的表格。

tab2 <- with(hpv2, stby(list(x=orxh55, y=orxh16), 
sex, ctable, prop="n", useNA="no", dnn = c("HPV_55", "HPV-16")))
Cross-Tabulation  
HPV_55 * HPV-16
Data Frame: hpv2
Group: sex = female

---------- -------- ---------- ---------- -------
HPV-16 negative positive Total
HPV_55
negative 2341 4 2345
positive 11 0 11
Total 2352 4 2356
---------- -------- ---------- ---------- -------

Group: sex = male

---------- -------- ---------- ---------- -------
HPV-16 negative positive Total
HPV_55
negative 2140 23 2163
positive 25 2 27
Total 2165 25 2190

关于r - 在ftable中添加列和行总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60154976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com