2 years ago

#6332

test-img

Doctor G

How to iterate over flextable columns

I want to iterate over several columns of a flextable using the mk_par function. Consider the following example:

tibble(a = c(1:10),
       b1 = letters[1:10],
       b2 = LETTERS[1:10],
       c1 = paste0("new_",letters[1:10]),
       c2 = paste0(LETTERS[1:10], "_new")) %>% 
  flextable(col_keys = c("a", "b", "c")) %>% 
  mk_par(j = "b", value = as_paragraph(b1, b2)) %>% 
  mk_par(j = "c", value = as_paragraph(c1, c2))

I would like to replace the two mk_par statements by a single expression which takes the arguments c("b", "c") and renders the same output. I have succeeded in rewriting this with a for loop

for(pref in c("b", "c")){
  tt <- tt %>% 
    mk_par(j = pref, 
         value = as_paragraph(.data[[paste0(pref,1)]],
                              .data[[paste0(pref,2)]]))
}

but I wonder if there is a one line expression that does the same which integrates smoothly in a dplyr pipe syntax?

r

flextable

0 Answers

Your Answer

Accepted video resources