gpt4 book ai didi

r - flextable:如何合并某些列的重复值的行

转载 作者:行者123 更新时间:2023-12-05 00:58:48 26 4
gpt4 key购买 nike

我正在使用 flextable() 制作表格。我想合并具有重复 srdr_id 的单元格。

鉴于这些数据:

test <- structure(list(srdr_id = c("175124", "175124", "172545", "172545", 
"172609", "172609", "172609"), full_name = c("TAU", "MI", "TAU",
"MI", "TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Assessed control", "Intervention", "Control", "Computer BI",
"Therapist BI"), arm_number = c(1L, 2L, 1L, 2L, 1L, 2L, 3L)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))


srdr_id full_name article_arm_name arm_number
<chr> <chr> <chr> <int>
1 175124 TAU Control 1
2 175124 MI WISEteens 2
3 172545 TAU Assessed control 1
4 172545 MI Intervention 2
5 172609 TAU Control 1
6 172609 MI Computer BI 2
7 172609 MI Therapist BI 3

我可以用下面的代码来做 - 但想简化多个 merge_at() 语句。

flextable(test) %>% theme_box() %>% 
merge_at(i = 1:2, j = 1) %>%
merge_at(i = 3:4, j = 1) %>%
merge_at(i = 5:7, j = 1)

<code>enter image description here</code>

不幸的是,当我添加另一个在常见 srdr_id 中重复的列时,简单的解决方案 merge_v(j = ~srdr_id) 不再足够。

test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525", 
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 9 x 4
srdr_id substances full_name article_arm_name
<chr> <chr> <chr> <chr>
1 175124 alcohol TAU Control
2 175124 alcohol MI WISEteens
3 172525 alcohol TAU Treatment as usual
4 172525 alcohol MI (parent) Brief MI (b-MI)
5 172545 cannabis TAU Assessed control
6 172545 cannabis MI Intervention
7 172609 "alcohol\n cannabis\n other drugs" TAU Control
8 172609 "alcohol\n cannabis\n other drugs" MI Computer BI
9 172609 "alcohol\n cannabis\n other drugs" MI Therapist BI

最佳答案

哇 - 我错过了简单案例的明显解决方案。问题已使用更真实(嵌套)的数据集进行编辑。

test_ft <- flextable(test) %>% theme_box() %>%  merge_v(j = ~srdr_id)

关于r - flextable:如何合并某些列的重复值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56327151/

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