Reputation: 619
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)
Upvotes: 1
Views: 4574
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"))
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"))
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