改变表格中地层的顺序。

huangapple go评论97阅读模式
英文:

Change order of strata in table

问题

尝试更改分层中 cyl 组的顺序为 6 Cylinder、4 Cylinder、8 Cylinder。

  1. library(tidyverse)
  2. library(gtsummary)
  3. tbl <-
  4. mtcars %>%
  5. select(am, cyl, mpg, hp) %>%
  6. dplyr::mutate(
  7. cyl = paste(cyl, "Cylinder"),
  8. am = factor(am, labels = c("Automatic", "Manual"))
  9. ) %>%
  10. tbl_strata(
  11. strata = cyl,
  12. ~.x %>%
  13. tbl_summary(
  14. by = am,
  15. type = where(is.numeric) ~ "continuous"
  16. ) %>%
  17. modify_header(all_stat_cols() ~ "**{level}**")
  18. )
英文:

Trying to change the order of the cyl groups within the strata to 6 Cylinder, 4 Cylinder, 8 Cylinder.

  1. library(tidyverse)
  2. library(gtsummary)
  3. tbl &lt;-
  4. mtcars %&gt;%
  5. select(am, cyl, mpg, hp) %&gt;%
  6. dplyr::mutate(
  7. cyl = paste(cyl, &quot;Cylinder&quot;),
  8. am = factor(am, labels = c(&quot;Automatic&quot;, &quot;Manual&quot;))
  9. ) %&gt;%
  10. tbl_strata(
  11. strata = cyl,
  12. ~.x %&gt;%
  13. tbl_summary(
  14. by = am,
  15. type = where(is.numeric) ~ &quot;continuous&quot;
  16. ) %&gt;%
  17. modify_header(all_stat_cols() ~ &quot;**{level}**&quot;)
  18. )

答案1

得分: 3

要更改分类变量的顺序,请将其转换为因子,并在levels部分指定顺序,如下所示:

  1. library(tidyverse)
  2. library(gtsummary)
  3. tbl <-
  4. mtcars %>%
  5. select(am, cyl, mpg, hp) %>%
  6. dplyr::mutate(
  7. cyl = paste(cyl, "Cylinder"),
  8. am = factor(am, labels = c("Automatic", "Manual")),
  9. cyl = factor(cyl, levels = c("8 Cylinder", "6 Cylinder", "4 Cylinder"))
  10. ) %>%
  11. tbl_strata(
  12. strata = cyl,
  13. ~.x %>%
  14. tbl_summary(
  15. by = am,
  16. type = where(is.numeric) ~ "continuous"
  17. ) %>%
  18. modify_header(all_stat_cols() ~ "**{level}**")
  19. )
  20. tbl

[![gtsummary table][1]][1]

  1. [1]: https://i.stack.imgur.com/8XIS5.png
  2. <details>
  3. <summary>英文:</summary>
  4. To change the order of a categorical variable, change it to a factor, and specify the order in the `levels` part as shown below:

library(tidyverse)
library(gtsummary)

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

  1. [![gtsummary table][1]][1]
  2. [1]: https://i.stack.imgur.com/8XIS5.png
  3. </details>

huangapple
  • 本文由 发表于 2023年6月29日 06:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定