Rmarkdown PDF tables, merge cells and return to line

919 views Asked by At

I am trying to integrate a survey in my pdf report, the survey is composed of three columns; one with the code, the second with the question and the third with the possible answers. I would like to get a result more or less like this:

enter image description here

library('flextable')

survey <- data.frame(a=c("code 1", "code 1","code 2","code 2","code 2"), b=c("this is a very very very very very very very long question","this is a very very very very very very very long question","this is also a very very very very very very very long question", "this is also a very very very very very very very long question", "this is also a very very very very very very very long question"), c=c("I agree","I don't", "yes","no","maybe"))

So I have basically two needs; to merge vertically the cells of columns a and b, and to break the line in column b where there are very long questions.

I tried to use flextable which works fine for merging cells, however, even specifying the width of the columns, where there is a merge the sentences are not returning to the line.

ft_merge <- flextable(survey)
ft_merge <- merge_v( ft_merge, j= ~ a + b)%>%
  width(ft_merge$a, width=0.1)%>%
width(ft_merge$b, width=2)%>%
  width(ft_merge$c, width=2)
ft_merge

Result:

enter image description here

I also tried to use Kable, but from what I read there is no option to merge the lines.

Finally, I tried to use Huxtable, but I keep getting an error related to the encoding (The survey is in French and contains a lot of accents.)

Could you suggest me another solution? Am I using flextable correctly?

Thank you!

1

There are 1 answers

0
David Gohel On

This has been fixed in the latest version of flextable (>=0.7.1).

library(flextable)
library(magrittr)

survey <- data.frame(
  a = c("code 1", "code 1", "code 2", "code 2", "code 2"), 
  b = c("this is a very very very very very very very long question", 
        "this is a very very very very very very very long question", 
        "this is also a very very very very very very very long question", 
        "this is also a very very very very very very very long question", 
        "this is also a very very very very very very very long question"), 
  c = c("I agree", "I don't", "yes", "no", "maybe"))

ft_merge <- flextable(survey)
ft_merge <- merge_v(ft_merge, j = ~ a + b) %>%
  width(j = "a", width = 0.5) %>%
  width(j = "b", width = 2) %>%
  width(j = "c", width = 2)


print(ft_merge, preview = "pdf")

enter image description here