I have something like this in my R environment
myoutput <- xtable(mtcars)
and i want to see the updated myoutput in latex automatically, is this possible?
many thanks in advance,
You can use the texPreview package.
library(xtable)
library(texPreview)
LaTeX <- xtable(mtcars)
tex_preview(LaTeX)
This code displays the LaTeX table in the RStudio viewer.
If you are talking about somefile.rmd (or just create one in R Studio with this - .rmd - extension) then try the following:
---
title: "Somefile"
subtitle: "Somefile subtitle"
author: "Your Name"
output:
beamer_presentation:
slide_level: 2
pandoc_args: "--latex-engine=xelatex"
fig_width: 5
fig_height: 5
header-includes:
- \usepackage{tikz, graphicx, multirow, colortbl, schemabloc}
- \usepackage[11pt]{moresize}
- ... # something else
---
## Overview of someproject
```{r echo = FALSE, message = FALSE, warning = FALSE, fig.align = "center", ...}
d <-
read.csv2("somefile.csv", header = TRUE, sep = ";", dec = ".") %>%
head(.)
Using this code you do the following:
You create a beamer presentation (smth like ppt)
In the section between --- ... --- you set your "global configuration" of the presentation
Using ## you create a new slide
Using {r echo = FALSE, message = FALSE, ...} you can insert R code that will appear on that slide.
Related
I am trying to make a RMarkdown report using bookdown::html_document2 to create numbered Fig. 1, Fig. 2, ... across the whole document. Here, I am using both the R-generated and the external figures. I have found that using include_graphics() will help to generate a proper Fig. X numbers, also including in numbering the external figures.
To get the script to work, I am declaring the root.dir = rprojroot::find_rstudio_root_file('C:/myRproject')) while my external figures are located within C:/myRproject/inImg. But in this case, R cannot find my external images anymore? Why is this and how can I properly claim the paths for my R Markdown input, and for external figures? Thank you!
Example:
---
title: "My awesome title"
author: "me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
toc_depth: 3
knit: (function(input, ...) {
rmarkdown::render(
input,
output_dir = "../outReports",
output_file = file.path("../outReports", glue::glue('test_{Sys.Date()}'
)))
})
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, tidy = TRUE, tidy.opts = list(comment = FALSE), message = F, warning = F)
knitr::opts_chunk$set(fig.width=6, fig.height=3)
library(knitr)
library(png)
```
```{css, echo=FALSE}
p.caption {
font-size: 0.8em;
}
```
```{r setup-root}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))
```
```{r read-libs, eval = TRUE, echo=FALSE, include = FALSE, warning = FALSE, error = FALSE }
# rm(list=ls())
getwd()
#### Source paths and functions -----------------------------------------------
source('myPaths.R') # already this one I can't find within the directory?
# Read pictures as part of teh R chunks
library(knitr)
library(png)
# Read Input data -------------------------------------------------------------------
#getwd()
load(file = "outData/dat1.Rdata")
```
## Including Plots
You can also embed plots, for example:
```{r, out.width = "50%", fig.cap = 'Add fig from internet'}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```
```{r add-extern-plot2, fig.cap = 'my numbered caption'}
# All defaults
img1_path <- "C:/myRproject/inImg/my_extern_fig.png"
img1 <- readPNG(img1_path, native = TRUE, info = TRUE)
attr(img1, "info")
include_graphics(img1_path)
```
I have recently decided to use pagedown package in producing pdf and html outputs and therefore installed the library. I am trying to run the very simple Rmd file that comes as default when I choose to use pagedown file as my new file in the RStudio.
Here is the Rmd file content if you would like to see;
---
title: "A Multi-page HTML Document"
author: "Yihui Xie and Romain Lesur"
date: "`r Sys.Date()`"
output:
pagedown::html_paged:
number_sections: FALSE
# uncomment this line to produce HTML and PDF in RStudio:
knit: pagedown::chrome_print
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
This is an example of a multi-page HTML document with some options shown in YAML header. See https://pagedown.rbind.io for the full documentation. The rest of this document is random text.
# Random text
```{r, results='asis', echo = FALSE}
random_markdown = function(len = 100) {
uri = knitr::image_uri(file.path(R.home('doc'), 'html', 'logo.jpg'))
text = function(len) {
trimws(paste(sample(c(letters, rep(' ', 10)), len, TRUE), collapse = ''))
}
id = function() paste(sample(letters, 8, TRUE), collapse = '')
figure = function(i = id()) {
sprintf('![(#fig:%s)The R logo.](%s){width=%d%%}', i, uri, sample(20:60, 1))
}
tab = paste(knitr::kable(head(mtcars[, 1:5])), collapse = '\n')
table = function(i = id()) {
c(sprintf('Table: (#tab:%s)A table example.', i), tab)
}
unlist(lapply(seq_len(len), function(i) {
if (i %% 20 == 0) return(paste('#', text(sample(10:30, 1))))
if (i %% 10 == 0) return(paste('##', text(sample(10:30, 1))))
# insure some elements
if (i == 3) return(text(50))
if (i == 4) return(figure("md-fig"))
if (i == 5) return(text(50))
if (i == 6) return(table("md-tab"))
# then random
type = sample(1:3, 1, prob = c(.9, .03, .07))
switch(type, text(sample(50:300, 1)), figure(), table())
}))
}
cat(random_markdown(), sep = '\n\n')
# Knitr inserted Figures and tables
## Simple graphics
```
Until here, R markdown can run the document well. However, when I tried to add the following two code chunks, the document fails to run.
``` {r simple-graphic, fig.cap = 'A very simple plot'}
plot(1)
```
## Simple tables
```{r simple-table}
knitr::kable(head(mtcars, 3), caption = "A Simple table")
```
And here is the error I get;
Error in force(expr) : Failed to generate output in 30 seconds (timeout).
Calls: <Anonymous> -> with_temp_loop_maybe -> with_loop -> force
Closing websocket connection
Closing browser
Cleaning browser working directory
Closing local webserver
I do not understand why the document does not fail to run in the first phase, while it fails to run in the second step. I tried to find a solution through web. I hope I am clear regarding my problem and I look forward to your reply. Thank you for your understanding beforehand.
If you just remove knit: pagedown::chrome_print the document will render to HTML just fine, Then from here, you can "print to PDF" from the browser to get both an HTML and a PDF doc of the output
---
title: "A Multi-page HTML Document"
author: "Yihui Xie and Romain Lesur"
date: "`r Sys.Date()`"
output:
pagedown::html_paged:
number_sections: FALSE
---
I think the issue might be your are specifying 2 different output formats, and Rmarkdown is taking a long time to render these
There is a similar issue discussed here the advice was to increase the timeout value, as it's default is 30 seconds until the process is fails out. and another similar issue here... but to be honest, I was not able to correct apply the timeout argument in chrome_print
I am trying generate automated reports using rmarkdown, and final output expected is pdf. However, when I run the script the resulting .Rmd file is okay, but the resulting .pdf file does not show the table. It just shows the table as a list of values. However, if I open the .Rmd file in RStudio, and use the kint button, I get a correctly formatted pdf file. Has anyone seen this behaviour before? am I missing something?
---
title: "RUO"
author: "Me"
date: "`r format(Sys.Date(), '%B %d, %Y')`"
always_allow_html: true
output:
pdf_document:
df_print: kable
keep_tex: true
latex_engine: lualatex
header-includes:
- \usepackage{graphicx}
- \usepackage{fancyhdr}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage[para,flushleft]{threeparttable}
- \usepackage{fontspec}
- \setmainfont{Raleway}
- \AtBeginDocument{\let\maketitle\relax}
classoption:
- twocolumn
---
\fancypagestyle{plain}{}
\pagestyle{fancy}
\addtolength{\headheight}{1.0cm}
\rhead{Name: John Doe\\Sex: Male\\DoB: 01.01.01\\Lab \#: XXXXXXXX\\MRN \#: XXXXXXXX}
```{r setup, warning = FALSE, message = FALSE, echo = FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(tidyverse)
library(stringi)
library(DESeq2)
library(kableExtra)
```
## This section is for Research Use Only
### Expression Table
```{r ExpTable}
df <- data.frame(cbind("gene_name" = c("AAA", "BBB", "CCC"),
"z-score" = c(-2, 2, 3)))
df %>%
setNames(c("Gene Name", "Z-score")) %>%
as.data.frame() %>%
# as_tibble() %>%
knitr::kable(booktabs = T) %>%
kableExtra::kable_styling(latex_options = c("hold_position", "striped")) # %>%
# kableExtra::column_spec(2, width = "3 cm")
```
\vfill
### Methodology
Some Description
### Comments and Limitations
Disclosures.
\clearpage
This code is the minimal example. When you use something like:
Rscript -e "library('knitr'); knitr::knit('filename.Rmd')"
The table does not render, but opening the same file in RStudio, renders is correctly.
UPDATE:
I realized after some more digging, that this is a un-reported bug (probably). If you render a rmarkdown with a table to pdf, then it will usually render correctly. But sometimes, the table is rendered as a list in the first render, and if you then render the same .Rmd to pdf, the table is rendered and correctly reformatted. So if you render the same file twice, the second time all the tables are correctly rendered. This happens more frequently if the only thing your file has a single table.
I use this rmd:
---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`"
---
## A function that generates sections
```{r setup, include = FALSE}
library(pander)
create_section <- function() {
# Inserts "## Title (auto)"
pander::pandoc.header('Title (auto)', level = 2)
# Section contents
# e.g. a random plot
plot(sample(1000, 10))
# a list, formatted as Markdown
# adding also empty lines, to be sure that this is valid Markdown
pander::pandoc.p('')
pander::pandoc.list(letters[1:3])
pander::pandoc.p('')
}
```
## Generate sections
```{r, results='asis', echo=FALSE}
n_sections <- 3
for (i in seq(n_sections)) {
create_section()
}
```
and then:
library(knitr);
library(rmarkdown);
setwd("C:/bla")
knit('test_md.Rmd')
rmarkdown::pandoc_convert("test_md.md", to = "pdf", output = "test_pdf.pdf")
This kind of works but the plots are all rendered after the sections:
Each section should contain the plot. Any ideas? Thanks!
PS:
Wrapping:
plot(sample(1000, 10))
in print:
print(plot(sample(1000, 10)))
forces output to be produced. Unfortunately, NULL is also printed underneath the plot.
Could you just add pdf_document in the YAML and then generate the PDF by knitting?
---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`"
output: pdf_document
---
I was able to get the same result you described when running the rmarkdown::pandoc_convert() on the .md file, all the plots at the end of the .PDF file.
I'd like to output my own YAML header in RMarkdown with Markdown output. The reason behind this is the dynamic creation of MD files from a given source.
To attempt to add it with results='asis' won't work as it will process the output for links, i.e: add <> to the links:
---
title: "test"
output:
md_document:
variant: markdown
toc: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r testyaml, echo=FALSE, results='asis'}
h <- "
+++\n
showonlyimage = false\n
draft = false\n
image = \"http://adsf.com\" \n
date = \"2016-11-05T18:25:22+05:30\"\n
title = \"mytitle\"\n
weight = 0\n
+++\n"
cat(h, sep = " ", fill = FALSE, collapse = '\n')
Output:
+++
showonlyimage = false
draft = false
image = "<http://adsf.com>"
date = "2016-11-05T18:25:22+05:30"
title = "mytitle"
weight = 0
+++
(Notice the <> wrapping http://adsf.com).
Set preserve_yaml: true, like this:
output:
md_document:
variant: markdown
preserve_yaml: true