I'm new to knitr
and Latex stuff, so this may be a very naive question, but I failed to find a correct answer.
I'm doing empirical research that sometimes, we need to add headnotes as instruction for a complex table.
Below is the code I'm currently using (in a file named test.Rnw
).
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{authblk}
\usepackage{float}
\usepackage{array}
\usepackage{booktabs}
\usepackage{mathptmx}
\usepackage{pdflscape}
\usepackage{fullpage}
\usepackage{cite}
\usepackage{color}
% packages intend to rotate table
\usepackage[graphicx]{realboxes}
\usepackage{adjustbox}
\usepackage{rotating}
\usepackage[top = 0.5in, bottom = 0.5in, left = 0.5in, right = 0.5in]{geometry}
\begin{document}
\section{TEST CODE}
<<Table_Test Test Table, echo=FALSE, results="asis", warning=FALSE, message=FALSE>>=
set.seed(138744)
df_1 <- data.frame("id" = c('a', 'a', 'a', 'b','b','b'),
'time' = c(1991,1991,1991, 2001,2003,2004),
'value' = c('x', 'y','x','z','w','u'))
table_instruction <-"This is only here to test whether the text is too long. This is only here to test whether the text is too long"
print(xtable(df_1,# first zero "represents" row numbers which we skip later
# align and put a vertical line (first "l" again represents column of row numbers)
align = paste0("ll", paste0(rep("c", dim(df_1)[2]-1), collapse = "")),
caption = "Test Table",
label='test-tab'),
floating = TRUE,
size="\\fontsize{8pt}{10pt}\\selectfont", #Change size; useful for bigger tables "normalsize" "footnotesize"
include.rownames = FALSE, #Don't print rownames
include.colnames = TRUE, #We create them ourselves
caption.placement = "top", #"top", NULL
hline.after=NULL, #We don't need hline; we use booktabs
# floating.environment = 'sidewaystable',# to rotate the table
# whether \begin{Table} should be created (TRUE) or not (FALSE)
sanitize.text.function = force, # Important to treat content of first column as latex function
add.to.row = list(pos = list(-1, -1, 0, nrow(df_1)),
command = c(paste0("\\toprule \n"),# NEW row
paste0("\\multicolumn{", dim(df_1)[2],"}{@{}l}{", table_instruction,"} \\\\" ,
"\\cmidrule(l){1-", dim(df_1)[2], "}"),
paste0("\\cmidrule(l){1-", dim(df_1)[2], "} \n"),
paste0("\\bottomrule \n \\multicolumn{",dim(df_1)[2],"}{l}",
"",paste("{\\scriptsize{", "***$p$< .001, **$p$< .01, *$p$< .05","}}",sep = " "),"\\\\"))
)
)
@
\end{document}
Then I render the above code using the code below:
rm(list=ls())
library("knitr")
knit2pdf('test.Rnw')
It works successfully, the problem is that the headnotes (right above the header row) is not self-contained to the table's width. Instead, it stretches the table way too wide.
Any suggestion on how to make the long headnotes, no matter how long, to have consistent width with the table?