6

I am trying to create a 'flexable' object from the R package "flextable". I need to put same column names in more than one columns. When I am putting them in the the "col_key" option in the function "flextable" I am getting the error of "duplicated col_keys". Is there a way to solve this problem?

a<-c(1:8)
b<-c(1:8)
c<-c(2:9)
d<-c(2:9)
A<-flextable(A,col_keys=c("a","b","a","b"))

This is the example code for which I am getting the error.

user438383
  • 5,716
  • 8
  • 28
  • 43
Bomvole
  • 61
  • 1
  • 4
  • Welcome! You're more likely to get answers if you edit your question to include a reproducible example of your problem - it is easier for others to help if they can see what your data and code looks like. See [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Jan Boyer Jun 07 '18 at 18:48
  • Thank you for the comment. I have added an example code. – Bomvole Jun 08 '18 at 14:11

3 Answers3

2

As it stands now, flextable does not allow duplicate column keys. However, you can achieve the same result by adding a row of "headers," or a row of column labels, to the top of your table. These headers can contain duplicate values.

You do this with the "add_header_row" function.

Here is a base example using the iris data set.

ft <- add_header_row(
  ft, 
  values = c("", "length", "width", "length", "width"), 
  top = FALSE 
)
ft <- theme_box(ft)

https://davidgohel.github.io/flextable/articles/layout.html

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
Max Baer
  • 21
  • 4
  • 1
    Although your answer could be 100% correct, it might also become 100% useless if that link is moved, changed, merged into another one or the main site just disappears... **:-(** Therefore, please [edit] your answer, and copy the relevant steps from the link into your answer, thereby guaranteeing your answer for 100% of the lifetime of this site! **;-)** You can always leave the link in at the bottom of your answer as a source for your material... – Piotr Labunski Feb 27 '20 at 21:14
2

I found a work around by adding the character \r to the column names to create unique column names :

library(flextable)
A <- matrix(rnorm(8), nrow = 2, ncol = 4)
A <- as.data.frame(A)
col_Names <- c("a","b","a","b")
nb_Col_Names <- length(col_Names)

for(i in 1 : nb_Col_Names)
{
  col_Names[i] <- paste0(col_Names[i], paste0(rep("\r", i), collapse = ""), collapse = "")
}

colnames(A) <- col_Names
tbl_A <- flextable(A)

Emmanuel Hamel
  • 1,769
  • 7
  • 19
1

Currently, using set_header_labels:

library(flextable)
a<-c(1:8)
b<-c(1:8)
c<-c(2:9)
d<-c(2:9)
A <- data.frame(a,b,c,d)
flextable(A) |> set_header_labels(`a` = "a", `b` = "b", `c` = "a", `d` = "b")
iago
  • 2,990
  • 4
  • 21
  • 27