如何在 tableone 包的 createtableone 命令中按行报告百分比?

How to report percentages by rows in createtableone command in tableone package?

提问人:Mohamed Rahouma 提问时间:8/31/2019 更新时间:9/1/2019 访问量:2010

问:

我想使用以下代码使用 r 中 tableone 包中的 CreateTableOne 按行报告百分比

vars<-c( "Group1vsGroup2", "Single.Institution",  
           "Internal.Funding",  "National.Funding", 
           "Industr1.Funding")

CatVar<-c(  "Single.Institution",  
           "Internal.Funding",  "National.Funding", 
           "Industr1.Funding")


tab2 <- CreateTableOne(vars = vars, strata = "Group1vsGroup2",factorVars = CatVar,data = df,test = T);tab2<-print(tab2, margin=1,test = T, varLabels = T,quote = T,dropEqual = T)

我添加了“margin=1”,正如我在这个网站上看到的那样,尽管它是用于 tableone 命令(不是 CreateTableOne),但我按列获得了 %,如下图所示。任何建议将不胜感激。enter image description here

R 百分比

评论

0赞 A. Suliman 8/31/2019
我不认为有理由管理方向。也许你应该尝试 cran.r-project.org/web/packages/Gmisc/vignettes/...,你可能需要做一个额外的打字,但你会得到很大的灵活性CreateTableOneGmischtmlTable
0赞 Mohamed Rahouma 9/1/2019
多谢。我现在正在尝试 Gamsc,但无法确定正确的命令。我浏览了 Gmisc 文档,但还无法分配它。有什么意见吗?

答:

4赞 A. Suliman 9/1/2019 #1

在这里,您可以开始使用 MWE,请参阅更多详细信息。?Gmisc::getDescriptionStatsBy

library(Gmisc)
# Define cyl as a factor so that getDescriptionStatsBy can use the correct Gmisc::describe*
mtcars$cyl=as.factor(mtcars$cyl)
getTable1Stats <- function(x, digits = 0,...){
  getDescriptionStatsBy(x = x, 
                        by = mtcars$am,
                        digits = digits,
                        header_count = TRUE,
                        ...)
}

t1 <- list()
t1[["Gas"]] <- getTable1Stats(mtcars$mpg, add_total_col="last")
#hrzl_prop=FALSE will indicate that the proportions are to be interpreted in a vertical manner
t1[["Cylinder&dagger;"]] <- getTable1Stats(mtcars$cyl, hrzl_prop=TRUE, add_total_col="last")
t1[["Disp"]] <- getTable1Stats(mtcars$disp, continuous_fn=describeMedian, add_total_col="last")

mergeDesc(t1,
  htmlTable_args = list(css.rgroup = "",
  caption  = "Basic descriptive statistics from the mtcars dataset",
  tfoot = "&dagger; The weight is in 10<sup>3</sup> kg")
)

enter image description here

PS:这个解决方案基于Max的小插曲。有关更多详细信息,您可以在此处查看其小插曲htmlTable

评论

0赞 Mohamed Rahouma 9/1/2019
伟大。非常感谢。在最后一列中,我们可以将 100% 放入每个单元格中吗?
0赞 A. Suliman 9/1/2019
我不这么认为,因为最后一列应该代表有多少辆汽车有 Cyl=4、6 和 8。但是,如果要这样做,可以在将表/输出发送到之前对其进行修改。下面是一个示例mergeDesccyl <- getTable1Stats(mtcars$cyl, hrzl_prop=TRUE, add_total_col="last");cyl[,3] <- c("11 (100%)", "7 (100%)", "14 (100%)" );t1[["Cylinder&dagger;"]]<-cyl
0赞 Mohamed Rahouma 11/14/2019
对不起,有没有办法以百分比报告小数点后 1 位,因为我注意到它报告的百分比没有任何小数位?
1赞 A. Suliman 11/14/2019
@MohamedRahouma只是更改了 getTable1Stats 中的变量,该变量默认为 0,即无小数。您可以更改定义函数或调用函数的时间。digitsdigits
0赞 Mohamed Rahouma 11/14/2019
多谢。它有效。无论如何,我有一些变量编码为 0 和 1,而我只需要知道表中的级别 1,因此无论如何都可以报告某个级别吗?