After multiple test and try I got a pdf from my script using knitr. Almost everything its right but I have some problems with default output: Date and sessionInfo. Also kableExtra library got me error.
I am not using R-studio...
Example of my script:
library(xtable)
library(knitr)
library(kableExtra)
#My first pdf with knitr
data(mtcars)
tabla=mtcars%>%
count(am)
kable(tabla, caption="tabla uno")
My commands to compile my script and get a pdf:
library(knitr)
setwd("C:/Users/Desktop")
knitr::stitch("C:/Users/Desktop/script.R")
In my pdf result below, you can see that pdf document begin with the date and finish with sessionInfo. I would like edit the date and put my own header and text and would like delete sessionInfo too. Also you can see that kable table is at the end of document and not in the correct order. Also I did try to add echo=FALSE, to avoid show command to make table but without success...:
I would suggest you create your document with a YAML header to set variables like author, date, and title. Then you can combine regular text with code chunks as below.
---
title: "Untitled"
author: "Rodrigo"
date: "9/9/2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(xtable)
library(knitr)
library(kableExtra)
```
# My first pdf with knitr
Some random text followed by a code block.
```{r}
# A comment
data(mtcars)
tabla=mtcars%>%
count(am)
```
Here's the table. The code that printed the table has been supressed with `echo = FALSE`.
```{r echo = FALSE}
kable(tabla, caption="tabla uno") %>%
kable_styling(latex_options = "hold_position")
```
More text
The output looks like this:
Related
I have a rmarkdown document where I import a few PDFs, and I would like to display four PDF-import-pages per page in my knitted PDF.
---
title: "combinePages"
author: "xxx"
date: '2022-xx-xx'
output:
pdf_document:
toc: true
header-includes:
- \usepackage{pdfpages}
---
\includepdf[pages={-}]{pdfs/Lecture1.pdf}
\includepdf[pages={-}]{pdfs/Lecture2.pdf}
Can this be done in rmarkdown?
According to the manual of pdfpages,
nup => Puts multiple logical pages onto each sheet of paper. The syntax of this option is: nup=⟨xnup⟩x⟨ynup⟩. Where ⟨xnup⟩ and ⟨ynup⟩ specify the umber of logical pages in horizontal and vertical direction, which are arranged on each sheet of paper. (Default: nup=1x1)
So, four pdf pages from an imported pdf file can be knitted per page using nup=2x2 in the option of \includepdf.
---
title: "combinePages"
author: "xxx"
date: '2022-xx-xx'
output:
pdf_document:
toc: true
header-includes:
- \usepackage{pdfpages}
---
## Multiple Page
\includepdf[pages={1-}, nup=2x2]{lorem_ipsum.pdf}
\includepdf[pages={1-}, nup=2x2]{lorem_ipsum.pdf}
So A page of the rendered document looks like this,
Explore the manual for more options.
I'm getting a weird error that I can't seem to understand. I have an rMarkdown file with a mixture of code, tables, and plain text (in RStudio).
I want to knit to PDF. I am able to do this, but only if I've deleted the cache folder. If the cache has been created, I get the following error when trying to do subsequent knits:
! LaTeX Error: Illegal character in array arg.
This is especially confusing as it always works the first time, and the PDF output looks exactly as I want it to. My code components are set to "cache=TRUE", because it's a big file and I want to cut down on loading time. I've looked up what that error means, but I can't find anything on how it relates to the cache.
If it's of any use, this is my header:
---
output:
pdf_document:
toc: yes
toc_depth: 4
number_sections: no
fig_caption: yes
latex_engine: xelatex
mainfont: Helvetica
font-family: Helvetica Neue
fontsize: 11pt
geometry: left=35mm, right=20mm, top=30mm, bottom=30mm
bibliography: resources/refs.bib
csl: resources/apa.csl
header-includes:
- \usepackage{fancyhdr} # Latex package for formatting PDFs.
- \pagestyle{fancy} # Set page style.
- \renewcommand{\headrulewidth}{1.5pt} # Thickness of header line.
- \setlength{\headheight}{13.59999pt} # Ensures consistent space between header line and text.
- \renewcommand{\href}[2]{#2\footnote{\url{#1}}} # Show URLs in footnote.
---
I can't directly share my data, but the setup for one of my tables looks like this:
exp2_age_gender_table %>%
kable("latex", booktabs = T) %>%
kable_styling(latex_options = "hold_position") %>%
column_spec(2, italic = TRUE) %>%
column_spec(4, italic = TRUE) %>%
row_spec(5, bold = TRUE)
The list of files contained in the created cache folder:
load-packages_0e5c21f97bd6e3c6091073c85b87d490.rdb
__packages
exp2-age-gend-table_009cc9300f71eb94b8251a5ed005e883.RData
exp2-age-gend-table_009cc9300f71eb94b8251a5ed005e883.rdb
exp2-age-gend-table_009cc9300f71eb94b8251a5ed005e883.rdx
exp2-age-gend-table-data_fc15cdaa97d5a922fc695858c44a93ac.RData
exp2-age-gend-table-data_fc15cdaa97d5a922fc695858c44a93ac.rdb
exp2-age-gend-table-data_fc15cdaa97d5a922fc695858c44a93ac.rdx
load-packages_0e5c21f97bd6e3c6091073c85b87d490.RData
load-packages_0e5c21f97bd6e3c6091073c85b87d490.rdx
raw-data_d44409d75a5aed8718bc355ff7b167fc.RData
raw-data_d44409d75a5aed8718bc355ff7b167fc.rdb
raw-data_d44409d75a5aed8718bc355ff7b167fc.rdx
My header looks as follows and works perfectly as intended:
---
header-includes:
- \usepackage{float}
- \usepackage{wrapfig}
- \usepackage{graphicx}
- \usepackage[fontsize=12pt]{scrextend}
- \usepackage{fontspec}
- \renewcommand*{\bibfont}{\footnotesize}
- \usepackage[dvipsnames]{xcolor}
output:
pdf_document:
latex_engine: xelatex
fig_caption: true
citation_package: biblatex
bibliography: SPP.bib
mainfont: ArialMT
geometry: margin=0.75in
---
However, the reference section already gets populated by the section name "References". Is there a way to stop that automated insertion? Thanks.
The "References" section is automatically included if you define a bibliography. Here an excerpt from the template:
$if(biblatex)$
\printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$
$endif$
Do you only want to change "References" into something else. Then it would be sufficient to add biblio-title: ... to you YAML header. If you want to suppress it completely, you have remove the quoted part in a copy of the template and use this copy instead. You can find the location where the template is stored via:
system.file("rmd", "latex", package = "rmarkdown")
#> [1] "/usr/lib/R/site-library/rmarkdown/rmd/latex"
Typically there are several files there:
list.files(system.file("rmd", "latex", package = "rmarkdown"))
#> [1] "default-1.14.tex" "default-1.15.2.tex" "default-1.17.0.2.tex"
#> [4] "default.tex"
The one with the highest version number (here default-1.17.0.2.tex) is used.
I used the following sql code in .Rmd document. However, I want to use the same SQL code in .Rnw document.
```{r label = setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, max.print = NA)
```
```{r, echo=FALSE, results='hide'}
library(DBI)
db <- dbConnect(RSQLite::SQLite(), dbname = "survey.db")
dbListTables(db)
```
```{sql, label = Q1, connection=db, tab.cap = "Table Caption"}
SELECT *
FROM Person;
```
Would prefer to get code formatting and output printing facility.
Porting the RMarkdown to RNW requires some tweaking:
Of course, chunk delimiters need to be adjusted: The RNW equivalent of ```{r, echo=FALSE} is <<echo=FALSE>>= and RNW chunks end with #. (See the minimal RNW example.)
Importantly, while chunks in RMarkdown documents always specify an engine, the engine in RNW is implicitly R unless the option engine is set. So ```{r} becomes simply <<>>=, but the equivalent of ```{sql} is <<engine="sql">>=.
RMarkdown includes some very useful magic when embedding SQL chunks, see knitr Language Engines: SQL on rmarkdown.rstudio.com. By default, results are rendered as a nice table and only the first 10 results are printed. In RNW, we need to take care of this on our own.
For embedding SQL in RMarkdown, note that the SQL connection must be passed to the SQL chunk via the connection option. The option output.var can be used to specify the name of the object to which the result of the query will be assigned.
A simple solution (see previous revision) would just assign the SQL result to an object, say res, using output.var and add another R chunk that prints res nicely, e.g. using xtable. However, there is a more elegant approach using hooks:
The example uses the SQLite sample database from sqlitetutorial.net. Unzip it to your working directory before running the code.
\documentclass{article}
\begin{document}
\thispagestyle{empty}
<<include=FALSE>>=
library(knitr)
library(DBI)
knit_hooks$set(formatSQL = function(before, options, envir) {
if (!before && opts_current$get("engine") == "sql") {
sqlData <- get(x = opts_current$get("output.var"))
max.print <- min(nrow(sqlData), opts_current$get("max.print"))
myxtable <- do.call(xtable::xtable, c(list(x = sqlData[1:max.print, ]), opts_current$get("xtable.args")))
capture.output(myoutput <-do.call(xtable::print.xtable, c(list(x = myxtable, file = "test.txt"), opts_current$get("print.xtable.args"))))
return(asis_output(paste(
"\\end{kframe}",
myoutput,
"\\begin{kframe}")))
}
})
opts_chunk$set(formatSQL = TRUE)
opts_chunk$set(output.var = "formatSQL_result")
opts_chunk$set(max.print = getOption("max.print"))
#
<<echo=FALSE, results="hide">>=
db <- dbConnect(RSQLite::SQLite(), dbname = "chinook.db")
#
<<engine = "sql", connection=db, max.print = 8, xtable.args=list(caption = "My favorite artists?", label="tab:artist"), print.xtable.args=list(comment=FALSE, caption.placement="top")>>=
SELECT * FROM artists;
#
\end{document}
A new chunk hook formatSQL is added. (Chunk hooks run whenever the corresponding chunk option is not NULL.) After a chunk with engine="sql", it reads the SQL results into sqlData. Then, it uses xtable to print the first max.print rows of the result.
By default, the chunk hook formatSQL is activated (i.e. it is globally set to TRUE) and SQL results are stored in formatSQL_result. The chunk option max.print controls the number of rows to be printed (set it to Inf to print all rows, always).
The table produced by xtable is highly customizable. The chunk option xtable.args is passed to xtable and print.xtable.args is passed to print.xtable. In the example these options are used to set a caption, a label and to suppress xtable's default comment.
Below the generated PDF. Note that syntax highlighting for non-R code in RNW requires installing highlight and adding the directory to path (Windows).
I am new to markdown and want to produce pdf files with the university (and other) logo on each page. I tried to use fancyheadings, and I have a problem:
Putting the image in the headings works only if I call the image in the document, otherwise the pdf is not produced
NB: I also had to set the heading height otherwise the page 2 would not work with - \setlength{\headheight}{2.4 cm}.
Any suggestions were the problem is?
(using knit in Rstudio, all freshly installed)
---
title: "Test"
author: "Author Name"
header-includes:
- \usepackage{fancyhdr}
- \usepackage{lipsum}
- \pagestyle{fancy}
- \rhead {\includegraphics{pictures/headers.pdf}}
- \fancyfoot[CO,CE]{}
- \setlength{\headheight}{2.4 cm}
- \fancyfoot[LE,RO]{\thepage}
geometry: top=2cm, bottom=3cm
output: pdf_document
abstract: This is a pandoc test . . .
---
\lipsum[1-20]
![](./pictures/headers.pdf)
this line needed or it doesnot make an output ???
\cleardoublepage
This is an R Markdown document.
the includegraphics works only if there is a picture in the document, maybe because of the latex template (?).
A solution is to create a cache picture (1white pixel picture) and call it at the end of the code: