887
887

Reputation: 619

How to add title to formattable?

I am making the following formattable. Since my data includes multiple groups (not included in the sample data), I will be subsetting my full data frame multiple times to create a table for each factor group in the Group column. I was wondering how I could add a title to the top of the table, so that I can see which subset the table is referring to. For these tables, I would like the title to simply be the value in the value in the Group column. So for the table below, the title would just be "1".

ex <- structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Var1 = c("A", "A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "C", 
"C", "C", "C", "C", "C"), Var2 = c("X", "X", "X", "X", "X", "X", 
"X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", 
"Y")), class = "data.frame", row.names = c(NA, -20L))
library(formattable)
formatex <- formattable(ex)

enter image description here

Upvotes: 1

Views: 4574

Answers (2)

user20276255
user20276255

Reputation: 21

formattable(ex, caption = ex$Group[1])

Upvotes: 1

Eric
Eric

Reputation: 2849

How is this? The code below adds Group 1 as title. If you want it to say just 1 then change the following caption = <insert title>.

library(magrittr)
library(knitr)
library(formattable)

ex <- structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Var1 = c("A", "A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "C", 
"C", "C", "C", "C", "C"), Var2 = c("X", "X", "X", "X", "X", "X", 
"X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", 
"Y")), class = "data.frame", row.names = c(NA, -20L))

formattable(ex) %>% 
  kable("html", escape = F, caption = "Group 1", align = c("l", "r", "r", "r", "r"))

enter image description here

OR

Literally apply the first value in Group as title. In this case, the title would be 1 as you alluded to in the body of your question.

formattable(ex) %>% 
  kable("html", escape = F, caption = ex$Group[1], align = c("l", "r", "r", "r", "r"))

enter image description here

TROUBLESHOOTING


library(magrittr)
library(knitr)
library(formattable)
library(kableExtra)

ex <- structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Var1 = c("A", "A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "C", 
"C", "C", "C", "C", "C"), Var2 = c("X", "X", "X", "X", "X", "X", 
"X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", 
"Y")), class = "data.frame", row.names = c(NA, -20L))

formattable(ex) %>% 
  kable("html", escape = F, caption = "Group 1", align = c("l", "r", "r", "r", "r")) %>% 
  kable_styling()

Upvotes: 2

Related Questions