改变表格中地层的顺序。

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

Change order of strata in table

问题

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

library(tidyverse)
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}**")
  )
英文:

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

library(tidyverse)
library(gtsummary)

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

答案1

得分: 3

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

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

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


[1]: https://i.stack.imgur.com/8XIS5.png

<details>
<summary>英文:</summary>

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

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


  [1]: https://i.stack.imgur.com/8XIS5.png

</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:

确定