Please help find a solution that allows one to merge multiple columns respective to a grouping column. In the reproducible example I want to merge columns v2 and v3 within the respective groups (a,b,c) only. Please use flextable.
# Sample data
dat <- data.frame(
v1 = c(rep("a", 3), rep("b", 3), rep("c", 3)),
v2 = c("G1", "G1", "G2", "G2", "G3", "G3", "G4", "G5", "G6"),
v3 = c(1, 1, 2, 2, 2, 5, 5, 5, 5),
v4 = c(1:9), stringsAsFactors = FALSE)
These previously answered questions are similar but not quite the answer. This question used a dummy variable but this only works with one other column and is not scalable.
dat$v_dummy <- paste0(dat$v1, dat$v2)
ft <- dat %>%
flextable() %>%
theme_box()
ft <- merge_v(ft, j =c("v1", "v_dummy"), target = c(1:2))
Another question merge cells vertically, but looses data (i.e. col v2 cel G2) in merge.
ft <- dat %>%
flextable() %>%
theme_box()
ft <- merge_v(ft, j = 1, target = 1:3)
Here is an example of the desired result
I think this answer the question:
library(flextable)
# Sample data
dat <- data.frame(
v1 = c(rep("a", 3), rep("b", 3), rep("c", 3)),
v2 = c("G1", "G1", "G2", "G2", "G3", "G3", "G4", "G5", "G6"),
v3 = c(1, 1, 2, 2, 2, 5, 5, 5, 5),
v4 = c(1:9), stringsAsFactors = FALSE
)
ft <- dat |>
flextable() %>%
theme_box() |>
merge_v(
j = c("v1")
) |>
merge_v(
j = c("v1", "v2"),
target = c("v2"),
combine = TRUE
) |>
merge_v(
j = c("v1", "v2", "v3"),
target = c("v3"),
combine = TRUE
)
ft