如何使用gt R包更改tab_spanner的级别。

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

How to change the levels of tab_spanner using gt R package

问题

这段代码生成的表格显示了变量 statisticp.value项目编号,但我想要相反的结果,即每个项目编号statisticp.value。如何实现?

英文:

The resulting table of this code gives the item no. for the variable statistic and p.value, but I want the inverse. I want statistic and p.value for each item no.. How can it be done?

library(tidyverse)
library(tidyr)
library(gt)

# shapiro-wilk test results
sw <- tibble(
  session = c(1, 1, 2, 2, 3, 3, 4, 4),
  item = c(1, 2, 1, 2, 1, 2, 1, 2),
  statistic = runif(8),
  p.value = runif(8)
)


sw_w <- sw %>%
  pivot_wider(names_from = item, values_from = c(statistic, p.value))

gt_tbl1 <- gt(sw_w, rowname_col = "session")

gt_tbl2 <- gt_tbl1 %>%
  # create column spanners as already indicated in the column names by "_"
  tab_spanner_delim(delim = "_") %>%
  # format percentage columns
  fmt_number(columns = 2:5, decimals = 3)

gt_tbl2 %>% tab_options(container.height = px(500))

答案1

得分: 1

也许有更简单的方法,但其中一个选项是根据项目编号重新排列您的数据列,以便每个项目编号的列相邻,并在tab_spanner_delim中使用split="first"

library(tidyverse)
library(tidyr)
library(gt)
library(dplyr, warn = FALSE)

set.seed(123)

# shapiro-wilk test results
sw <- tibble(
  session = c(1, 1, 2, 2, 3, 3, 4, 4),
  item = c(1, 2, 1, 2, 1, 2, 1, 2),
  statistic = runif(8),
  p.value = runif(8)
)

sw_w <- sw %>%
  pivot_wider(names_from = item, values_from = c(statistic, p.value))

gt_tbl1 <- sw_w |>
  select(session, ends_with("1"), ends_with("2")) |>
  gt(rowname_col = "session")

gt_tbl2 <- gt_tbl1 %>%
  tab_spanner_delim(delim = "_", split = "first") %>%
  fmt_number(columns = 2:5, decimals = 3)

gt_tbl2 %>%
  tab_options(container.height = px(500))

如何使用gt R包更改tab_spanner的级别。

英文:

Perhaps there is an easier approach but one option would be to reorder the columns of your data according to the item number such that columns for each item number are next to one another and using split=&quot;first&quot; in tab_spanner_delim.

library(tidyverse)
library(tidyr)
library(gt)
library(dplyr, warn = FALSE)

set.seed(123)

# shapiro-wilk test results
sw &lt;- tibble(
  session = c(1, 1, 2, 2, 3, 3, 4, 4),
  item = c(1, 2, 1, 2, 1, 2, 1, 2),
  statistic = runif(8),
  p.value = runif(8)
)


sw_w &lt;- sw %&gt;%
  pivot_wider(names_from = item, values_from = c(statistic, p.value))

gt_tbl1 &lt;- sw_w |&gt;
  select(session, ends_with(&quot;1&quot;), ends_with(&quot;2&quot;)) |&gt;
  gt(rowname_col = &quot;session&quot;)

gt_tbl2 &lt;- gt_tbl1 %&gt;%
  tab_spanner_delim(delim = &quot;_&quot;, split = &quot;first&quot;) %&gt;%
  fmt_number(columns = 2:5, decimals = 3)

gt_tbl2 %&gt;% tab_options(container.height = px(500))

如何使用gt R包更改tab_spanner的级别。

huangapple
  • 本文由 发表于 2023年5月22日 23:39:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307835.html
匿名

发表评论

匿名网友

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

确定