Jordan Hackett
Jordan Hackett

Reputation: 749

R flextable vertical merge conditional on another column

In the example below I would like to vertically merge like values in column 1 and then vertically merge like values in column 2 conditional on them being in the same group in column 1. Right now it currently merges "G2" across groups "a" and "b" from v1, which is not what I'd like. Is there a way to achieve this using a built in flextable function or like wise?

library(flextable)

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:9), stringsAsFactors = FALSE)

ft <- regulartable(dat)
ft <- merge_v(ft,j=c(1:2))

Expected output

Upvotes: 1

Views: 1227

Answers (1)

David Gohel
David Gohel

Reputation: 10695

I would create a variable for that (and use it but not display it):

library(flextable)

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:9), 
                  stringsAsFactors = FALSE)
dat$v_dummy <- paste0(dat$v1, dat$v2)
ft <- flextable(dat, col_keys = c("v1", "v2", "v3"))
ft <- theme_box(ft)
ft <- merge_v(ft, j = c("v1", "v_dummy"), target = c("v1", "v2"))
ft

enter image description here

Upvotes: 3

Related Questions