gpt4 book ai didi

Is possible to do a table with two group by with tbl_summary in R?(是否可以在R中使用tbl_sum创建一个包含两个GROUP BY的表?)

转载 作者:bug小助手 更新时间:2023-10-25 22:14:25 27 4
gpt4 key购买 nike



I'm working with the mtcars database, and I'm using the tbl_summary function. What I'm trying to do is to have two group by's, first with the type of transmission and then with the number of cylinders, so I will have six columns in total for the group by's plus the overall column, until now I have only been able to do the group by with one variable only.

我使用的是mtars数据库,并且使用的是tbl_sum函数。我尝试做的是有两个分组依据,首先是传动类型,然后是气缸的数量,所以我总共有六列分组依据加上总列,到目前为止,我只能用一个变量来计算分组依据。


This is my code:

这是我的代码:


mtcars2 <- within(mtcars, {
vs <- factor(vs, labels = c("V", "S"))
am <- factor(am, labels = c("Automatic", "Manual"))
cyl <- ordered(cyl)
gear <- ordered(gear)
carb <- ordered(carb)
})

mtcars2 %>%
tbl_summary(
by = cyl,
type = all_continuous() ~ "continuous2",
statistic = list(all_continuous() ~ c("{mean} ({sd})",
"{min}, {max}",
"{skew}"),
all_categorical() ~ "{n} / {N} ({p}%)"),
digits = all_continuous() ~ 1,
label = list(mpg ~ "Miles/ Gallon", disp ~ "Displacement (cu.in.)", hp ~ "Gross Horsepower", drat ~ "Rear Axle Ratio", wt ~ "Weight (1,000 lbs)", qsec ~ "1/4 Mile Time", vs ~ "Engine (Shape)", am ~ "Transmission", gear ~ "No. of Forward Gears", carb ~ "No. of Carburetors")
) %>%
add_overall() %>%
modify_header(label ~ "**Variable**") %>%
modify_spanning_header(c("stat_1", "stat_2", "stat_3") ~ "**Number of Cylinders**") %>%
modify_caption("**Table 1. Descriptive Statistics**") %>%
add_stat_label(label = all_continuous() ~ c("Mean (SD)", "Range", "Skew"))

更多回答
优秀答案推荐

You can use the tbl_strata() function to stratify the tbl_summary() by a second by variable. Example below!

您可以使用tbl_strata()函数按第二个by变量对tbl_sum()进行分层。下面是一个例子!


library(gtsummary)

tbl <-
mtcars %>%
select(am, cyl, mpg, hp) %>%
dplyr::mutate(
cyl = paste(cyl, "Cylinder"),
am = factor(am, labels = c("Automatic", "Manual"))
) %>%
tbl_strata(
strata = cyl,
~.x %>%
tbl_summary(
by = am,
type = where(is.numeric) ~ "continuous"
) %>%
modify_header(all_stat_cols() ~ "**{level}**")
)

enter image description here
Created on 2022-01-03 by the reprex package (v2.0.1)

由reprex包(v2.0.1)创建于2022-01-03


更多回答

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