header on each page of big table of xtable? - r

How do you put on a big table of xtable the table header on each page?, So that is easier to read the table the table between pages.
I use the following in Sweave:
test.big<- xtable(test,label="table",caption='test')
align(test.big) <- "|c|c|c|c|l|c|c|c|"
print(test.big,tabular.environment='longtable',include.colnames = TRUE,floating=FALSE)
Thanks for your answers

I think a better answer for this question is provided here: Column names on each page with xtable in Sweave
What if you want to edit your table in R? The solution above edits the output, so you won't need to add those lines in your longtable code manually. Thus this works better:
print(test.big, tabular.environment='longtable', include.colnames = TRUE,
floating=FALSE, add.to.row = list(pos = list(0), command = "\\hline \\endhead "))
Note that you can add several arguments in your add.to.row list:
print(test.big, tabular.environment='longtable', include.colnames = TRUE,
floating=FALSE, list(pos = list(seq(1,nrow(get(groups[i])), by = 2), 0),
command = c("\\rowcolor[gray]{.95} ","\\hline \\endhead ")))
You'll have to add this to your Sweave file:
\usepackage{colortbl}
This produces gray filling on every second row & header for each page.

The longtable (LaTeX) package specification can be found at that URL. The section of code in the examples whose output appears on pages 2 and 3 is in section 8 and I have reproduced bit of it below:
\caption[]{(continued)}\\
\hline\hline
\multicolumn{2}{#{*}c#{*}}%
{This part appears at the top of every other page}\\
\textbf{First}&\textbf{Second}\\
\hline\hline
\endhead
When they say on "every other page", they mean every page other than the first, which had a different header. If the xtable call is not working out of the box without any editing, then you should first check that you have the longtable package specified in your LaTeX preamble:
\usepackage{longtable}

Related

Format R Markdown output so that it can be copied and pasted to twitter

Trying to do daily reports with Rmarkdown on covid-19 data. Want to tweet top 10 values from tables, but the options tried so far leave no spaces - tabs are erased when the tweet button is pushed. Have tried {kableExtra} with html output and {flextable} with word output, but when copied and pasted, the column separations are 'disappearing' tabs.
Does anyone have any recommendations on how to obtain a table with spaces or commas between columns?
Example Rmarkdown script is here, if interested, but the question is meant to be general and not require looking at the script.
How about creating a picture of the table (which looks quite good then).
You could do this like this:
library("knitr")
library(kableExtra")
knitr::kable(mtcars, "latex") %>%
kableExtra::kable_styling(latex_options = "striped") %>%
kableExtra::save_kable("test.png")
Or does this have any downsides you don't want?
Addition:
Alright, I didn't look at your file - seems you want to add 4 tables but not copy 4 images.
Short question here - isn't this then quite hard with the 280 char limit of twitter...?
But what you could do is the following:
```{r, echo = F}
aa <- knitr::kable(head(mtcars[, 1:4]), "pipe")
for (i in 1:length(aa)) {
aa[i] <- gsub(" ", ",", aa[i])
aa[i] <- paste(aa[i], "\n")
}
aa
```
In your code chunk save the table to a variable. This will then just be a table in markdown format. Now you can parse through and replace and alter chars how you need it.

Is it possible to include a footnote without symbol in KableExtra?

When I use add_footnote("Footnote 1"), KableExtra always introduce a symbol in the footnote. But in many occasions, I would like to include a footnote without a symbol. For example, I would like to use add_footnote("Source: Consumer Expenditure Survey") to include information about the source of the data. But I do not want to have the symbol in front of "Source..." in my table. Is that possible?
Now you can. :)
With current dev ver (should be on CRAN in a week or so), there is a new function called footnote. To get some non-labeled footnotes, just type
mtcars[1:5, 1:5]%>%
kable("latex", booktabs = T)%>%
footnote(general = c("Note 1", "Note 2"), general_title = "")
Similar for html tables.
I don't think so if you want to use kableExtra. If you're producing your document in LaTeX, see https://tex.stackexchange.com/questions/30720/footnote-without-a-marker for a way to do it in pure LaTeX.

Use loop to generate section of text in rmarkdown

I need to produce a report that is composed of several sections, all sections look similar, with only some differences in data. The number of sections is also dependent on the data. What I ultimately want to have is something like this:
```{r}
section_names = c("A","B","C")
section_data = c(13,14,16)
```
# some looping mechanism here with variable i
This is section `r section_names[i]`
This section's data is `r section_data[i]`
#more things go here for the section
#end of loop should go here
The result should be a single html/document with all the sections one after the other.
Can you point me to a way for producing such an Rmd file with the loop?
Ideally I would have hoped to see something like in PHP:
<$php for(i=0;i<10;i++) { ?>
## some html template + code chunks here
<$php } ?>
This question is similar to that one, although it is LateX/RNW based. Besides, this answer demonstrates how to generate a rmarkdown document dynamically. However, neither of the questions is a exact duplicate of this one.
Basically, there are two mental steps to take:
Figure out the markdown markup needed per section. This could be something along the lines of
## This is section <section_name>
Section data is `<section_data>`.
Additional section text is: <section_text>.
Write R code that generates this markup, replacing the placeholders with the appropriate values.
For step 2, using sprintf is a natural candidate to combine static and dynamic text. Don't forget to use the chunk options results = "asis" to prevent knitr from adding formatting to your output and use cat (instead of print) to prevent R from adding additional stuff like quotes and element numbers.
I changed the input data structure a little bit for the sake of clarity (using a data.frame instead of independent vectors section_names and section_data).
```{r echo = FALSE, results = "asis"}
input <- data.frame(
name = LETTERS[1:4],
data = runif(n = 4),
text = replicate(4, paste(sample(x = LETTERS, size = 100, replace = TRUE), collapse = "")),
stringsAsFactors = FALSE)
template <- "## This is section %s
Section data is `%0.2f`.
Additional section text is: %s.
" # dont't forget the newline
for (i in seq(nrow(input))) {
current <- input[i, ]
cat(sprintf(template, current$name, current$data, current$text))
}
```
Output:
This is section A
Section data is 0.83.
Additional section text is: PUFTZQFCYJFNENMAAUDPTWIKLBSVKWMJWODFHSPRJRROTVDGNEROBVQPLLMVNPOUUHGVGRPMKAOAOMVYXKMGMUHNYWZGPRAWPYLU.
This is section B
Section data is 0.49.
Additional section text is: PFTYCGFSGSMAYSSCZXWLNLDOQEBJYEVSJIYDJPEPSWQBNWJVRUKBTYIUSTOICFKJFEJCWCAYBCQSRTXUDEQLLXCZNPUKNLJIQJXE.
This is section C
Section data is 0.58.
Additional section text is: FCJDDDMNLBUSJMCZVSBPYWCKSFJEARBXXFPAGBTKCWKHPEDGYWYTNGLVGQGJAFZRUMNSDCHKTTMGRFNSUZKFLOUGNWHUBNLVMGDB.
This is section D
Section data is 0.52.
Additional section text is: YQIXHABFVQUAAYZNWTZXJDISSLTZJJAZOLJMJSXEENFTUOFOTYKDNNUMFDXLJSWZEVDLCLSYCTSMEXFLBVQYRTBEVZLCTEBPUGTT.
Just sharing the approach I've used eventually.
I wrote a markdown file for the section. prepared the data for each section in the master document, and looped over all the sections I needed, each time calling to knit_child() with the section Rmd.
I know this is late, but I used this in my code to make numbered sections and it works a treat.
for (k in 1:length(listcsv)){ #Begin Loop at pdf file one and continue until all have been completed
subsection <- paste("5", k, sep = ".")}
this uses the loop number (k) to create the subsection number and then paste it against the section number. This happens to be in section 5, but you could use the same principle to make sections and subsections ad infinitum.

Adding section headers in between xtable figures in a loop

I am using knitr to generate a PDF writeup. I want to print a series of tables with section headers in between. I am doing this in an R code chunk. Unfortunately though, what happens is that the first header prints, then a figure, then the rest of the headers fit on that page and the rest of the tables come after rather than being interspersed amongst the headers as desired.
After this page there are a series of 5 more tables on their own pages.
This is the code that I am using:
dfList <- list(alc_top, alc_bottom, cpg_home_top, cpg_home_bottom, electronics_top, electronics_bottom)
labels <- c("Premium Liquor Brand - Top Performers", "Premium Liquor Brand- Bottom Performers", "CPG Home - Top Performers", "CPG Home - Bottom Performers", "Electronics - Top Performers", "CPG Home - Bottom Performers")
for (i in 1:length(dfList)) {
df <- dfList[[i]]
product = "test"
cat(paste("\\section{",labels[i],"}", sep=""))
print(xtable(df,size="\\tiny"))
}
I've tried adding a new line, cat("\\newpage") within the loop. this adds a new page for each label, but all of the graphs are after the new section again.
I think I need to specify a positioning value (H or h or something like that in LaTex) for the table, but I am not really sure how to do that with xtable and knitr.
The problem here is not the order in which the elements are written to the TEX file. The "wrong order" in the PDF is due to the fact that the tables are wrapped in floating environments and therefore the position of their TEX code in the source file does not necessarily correspond to the table's position in the PDF.
Here are three options that keep the tables at a fixed position. Each one has its pros and cons:
Option 1: Don't use floats
print.xtable has a floating argument (which defaults to TRUE). Setting this argument to FALSE results in a table that is not wrapped in a floating environment (default: table).
Pro: Simple and effective.
Con: Non-floats are not numbered, have no caption and no label. print.xtable ignores the caption and label arguments on xtable if floating = FALSE.
Option 2: Position "H"
print.xtable has a table.placement argument that can be used to pass a custom float placement specifier to the floating environment. The specifier H "places the float at precisely the location in the LaTeX code" (source: Wikibooks). Note that this requires \usepackage{float}.
Pro: Keep caption, numbering and label.
Con: Requires an additional package (hardly relevant).
Option 3: \FloatBarrier
The LaTeX package placeins offers a \FloatBarrier command which forces that all floats that are not displayed up to this point are printed.
Pros and cons: As option 2.
Besides, it clutters the code a little bit because of the \FloatBarrier commands that need to be inserted after each table – unless (at least in the specific case of this question) the following feature is used:
The package even provides an option to change the definition of \section to automatically include a \FloatBarrier. This can be set by loading the package with the option [section] (\usepackage[section]{placeins}). [source: Wikibooks]
Demo
\documentclass{article}
\usepackage{float}
\usepackage{placeins}
\begin{document}
<<results = "asis", echo = FALSE>>=
library(xtable)
# This table floats.
print(
xtable(head(cars),
caption = "Floating",
label = "tab:floating"), table.placement = "b"
)
# This table won't float but caption and label are ignored.
print(
xtable(head(cars),
caption = "Not floating",
label = "tab:not-floating"),
floating = FALSE)
# Placement "H". (requires "float" package)
print(
xtable(head(cars),
caption = "Non-floating float",
label = "tab:not-actually-floating"),
table.placement = "H")
cat("Text before the barrier. (text 1)")
# Floats won't float beyond this barrier (requires "placeins" package)
cat("\\FloatBarrier\n")
cat("Text after the barrier. (text 2)")
#
Add \texttt{table.placement = "b"} to the first table to see that it will be located at the bottom of page 1 (after `text 1') and `text 2` will come \emph{after} it (on page 2), althogh there would be plenty of space on page 1. This is because the float cannot `pass' the barrier.
\end{document}

xtable italics format for a column

I need to insert the species names in a table created by xtable in my Rnw file and I want to convert the relative column to italics format. Is it possible without any manual intervention?
My call is:
xtable(cklist, caption="Checklist...", align='lllc',label = 'tab:ckzygo')
To typeset a column in italics (or any other non-standard font shape), you should use the >{\cmd} syntax for column specification.
Assigning the column type >{\itshape}l generates a left-justified column in italics.
This is a better solution than iris$Species <- paste0("\\textit{", iris$Species, "}") as suggested in the comments because you neither have to modify your data nor you need to disable text sanitizing.
Small illustration:
\documentclass{article}
\usepackage{array}
\begin{document}
<<xtableItalics, results = "asis">>=
library(xtable)
print(xtable(head(iris), align = c(rep("l", 5), ">{\\itshape}l")))
#
\end{document}
The PDF looks like:
Please note that you need to use the array package for this to work.
EDIT: To show the flexibility of this approach, two more examples:
print(xtable(head(iris), align = c(rep("l", 5), ">{\\textit\\bgroup}l<{\\egroup}")))
print(xtable(head(iris), align = c(rep("l", 5), ">{\\textcolor{red}\\bgroup}l<{\\egroup}")))
The first line uses \textit{} instead of \itshape to typeset the italics. As \textit{} requires the text to modify as an argument, we need a slightly more complex syntax. (It's described in the wikibooks.org article linked above.)
This syntax can also be used to change for example the color of the text. In more complex cases, lrbox is required, as described in the linked article.

Resources