英文:
How to change the levels of tab_spanner using gt R package
问题
这段代码生成的表格显示了变量 statistic
和 p.value
的项目编号
,但我想要相反的结果,即每个项目编号
的 statistic
和 p.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))
英文:
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="first"
in tab_spanner_delim
.
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论