I found this great tutorial on how to modify the css formatting of a HTML report created with markdown and knitr in Rstudio. The post can be found here.
I was hoping to build on this concept and mimic the layout of the page here by using the same css. I tried to simply copy/paste/combine the two css files I found when I viewed the page's source.
Any help you can lend would be greatly appreciated! This is my first attempt and doing anything CSS.
This is the method provided by RStudio: http://www.rstudio.com/ide/docs/authoring/markdown_custom_rendering
options(rstudio.markdownToHTML =
function(inputFile, outputFile) {
require(markdown)
markdownToHTML(inputFile, outputFile, stylesheet='custom.css')
}
)
I've never been able to get that working properly so I do it a little differently:
I do this by creating the standard output file, then dropping the header and css code at the top in R:
tmp <- readLines("your.html")
tmp <- tmp[-c(1:50)] # or however many lines it is before the css ends
write(tmp,"your.html")
Then I use pandoc to add my own css in a standalone file
system("pandoc -s -S your.html -c your.css -o output.html")
Outside of RStudio (may work in it too - I'm not sure as I don't use it much), you can use option 'markdown.HTML.stylesheet' to set a custom style sheet. It will then import everything from your .css file into the newly created html file.
Here is an example:
## Set file names
htmlName <- "test.html"
rmdName <- gsub("html","Rmd", htmlName)
stylesheetName <- 'style.css'
## Generate rmd file from R
sink(file = rmdName, type='output')
cat('\n<textarea maxlength="3000" cols="70">')
cat("Hello World!")
cat('</textarea>\n')
sink()
## Generate style sheet from R
sink(file = stylesheetName, type='output')
cat("textarea {color: #a10000; }\n")
sink()
## Set knitr options and knit html
require(knitr)
options(markdown.HTML.stylesheet = stylesheetName)
knit2html(rmdName, output = htmlName)
Related
I am reading ISL at the moment which is related to machine learning in R
I really like how the book is laid out specifically where the authors reference code inline or libraries for example library(MASS).
Does anyone know if the same effect can be achieved using R Markdown i.e. making the MASS keyword above brown when i reference it in a paper? I want to color code columns in data frames when i talk about them in the R Markdown document. When you knit it as a HTML document it provides pretty good formatting but when i Knit it to MS Word it seems to just change the font type
Thanks
I've come up with a solution that I think might address your issue. Essentially, because inline source code gets the same style label as code chunks, any change you make to SourceCode will be applied to both chunks, which I don't think is what you want. Instead, there needs to be a way to target just the inline code, which doesn't seem to be possible from within rmarkdown. Instead, what I've opted to do is take the .docx file that is produced, convert it to a .zip file, and then modify the .xml file inside that has all the data. It applies a new style to the inline source code text, which can then be modified in your MS Word template. Here is the code:
format_inline_code = function(fpath) {
if (!tools::file_ext(fpath) == "docx") stop("File must be a .docx file...")
cur_dir = getwd()
.dir = dirname(fpath)
setwd(.dir)
out = gsub("docx$", "zip", fpath)
# Convert to zip file
file.rename(fpath, out)
# Extract files
unzip(out, exdir=".")
# Read in document.xml
xml = readr::read_lines("word/document.xml")
# Replace styling
# VerbatimChar didn't appear to the style that was applied in Word, nor was
# it present to be styled. VerbatimStringTok was though.
xml = sapply(xml, function(line) gsub("VerbatimChar", "VerbatimStringTok", line))
# Save document.xml
readr::write_lines(xml, "word/document.xml")
# Zip files
.files = c("_rels", "docProps", "word", "[Content_Types].xml")
zip(zipfile=out, files=.files)
# Convert to docx
file.rename(out, fpath)
# Remove the folders extracted from zip
sapply(.files, unlink, recursive=TRUE)
setwd(cur_dir)
}
The style that you'll want to modify in you MS Word template is VerbatimStringTok. Hope that helps!
I have an interactive Rmarkdown document which embeds a few shiny apps that generates graphs based on user inputs.
After I am happy with the graphs generated, I would like to save the report (so that it becomes static).
I have opened the report in my browser (Chrome), and tried printing to pdf. It sort of works, however some figures are cut into two by the page break.
Does anyone know what is the best way to print/save such reports?
I think it's a bit tricky but this is what i use on my app to save html plot on pdf or png format.
Instal wkhtmltopdf
wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command
line tools to render HTML into PDF and various image formats using the
Qt WebKit rendering engine. These run entirely "headless" and do not
require a display or display service.
Use it in R
This allow you to convert a htmlfile into pdfor img.
In my ShinyApp i use inside a downloadHandler() function somthing like this :
system("wkhtmltopdf --enable-javascript --javascript-delay 2000 plot.html plot.pdf")
I think for your example you could simply convert your html by using :
system("wkhtmltopdf yourFile.html yourFile.pdf")
You can give a download button on the ui.R as:
downloadButton('report', 'Download PDF')
And the corresponding server.R code:
library(knitr)
output$report = downloadHandler(
filename = function() {
paste("Report_", <date/identifier>, ".pdf", sep="")
},
content = function(file) {
rnw <- normalizePath('input.rnw') # assuming you wrote the code to display the graphs etc in this file
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(rnw, 'input.rnw')
out = knit2pdf(rnw, clean=TRUE)
file.rename(out, file)
}
)
With the Rmd files on root (eg. on my /knitr-jekyll/) they are turning into md files, but not on html files. Thus, they appear as simple markdown text.
I tried to put them on /_source and on /_posts but it get's worse, in this case I also don't get the md files.
I found creating a separate folder all together solves the problem.
/kintr-jekyll/_rmd/test.Rmd
But do remember that when you knit your Rmd to md that you knit to the _post folder if you using the standard bootstrap template. Also make sure that you specified your figure output. Easiest is to write some function which does this for you:
KnitPost <- function(input, base.url = "/") {
require(knitr)
opts_knit$set(base.url = base.url)
fig.path <- paste0("figures/", sub(".Rmd$", "", basename(input)), "/")
opts_chunk$set(fig.path = fig.path)
opts_chunk$set(fig.cap = "center")
render_jekyll()
knit(input, envir = parent.frame())
Lastly, go make sure in your .md file in knitr-jekyll/_post that the figures are clearly referenced. This should be within your test.md:
<img align="middle" src="/figures/test/test_image.jpg">
This link might help: R-Bloggers post about jekyll
I have a shiny app that allows the user to download an HTML file (knitted from a .Rmd file) that includes the code used to run the analysis based on all the user inputs. I am trying to write the base .Rmd file that gets altered when user inputs vary. I am having trouble including user input variables (e.g. input$button1) into R code chunks. Say the user input for input$button1 = "text1".
```{r}
results <- someFun(input$button1)
```
And I'd like to have it knitted like this:
```{r}
results <- someFun('text1')
```
Every time I download the knitted HTML though, I get input$button1 getting written to file. I would also like to be able to produce an .Rmd file that is formatted with this substitution. It seems like knit_expand() might be the key, but I can't seem to relate available examples to my specific problem. Is the proper way to knit_expand() the whole .Rmd file and specify explicitly all the parameters you want subbed in, or is there a more elegant way within the .Rmd file itself? I would prefer a method similar to this, except that instead of using the asis engine, I could use the r one. Any help would be greatly appreciated. Thanks!
Got it. Solution below. Thanks to Yihui for the guidance. The trick was to knit_expand() the whole .Rmd file, then writeLines() to a new one, then render. With hindsight, the whole process makes sense. With hindsight.
For the example, p1 is a character param 'ice cream' and p2 is an integer param 10. There is a user-defined param in ui.R called input$mdType that is used to decide on the format provided for download.
Rmd file:
Some other text.
```{r}
results <- someFun("{{p1}}", {{p2}})
```
in the downloadHandler() within server.R:
content = function(file) {
src <- normalizePath('userReport.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'userReport.Rmd')
exp <- knit_expand('userReport.Rmd', p1=input$p1, p2=input$p2)
writeLines(exp, 'userReport2.Rmd')
out <- rmarkdown::render('userReport2.Rmd', switch(input$mdType,
PDF = pdf_document(), HTML = html_document(), Word = word_document()))
}
file.rename(out, file)
}
Resulting userReport2.Rmd before rendering:
```{r}
results <- someFun("ice cream", 10)
```
Is there a way to print, from within R, a LaTeX table directly to an image file (for inclusion in another document/webpage). Basically, I'd like to supply LaTeX code to a function that saves it as an image to the working directory.
Pipe dreams?
There are various LaTeX-to-Image converter scripts, designed to do things like convert equations into images for including on web pages.
If you can find one of those (dvipng perhaps?) then you can go from a table in R to LaTeX easy enough and then from LaTeX to png.
If you have dvipng, you can leverage Hmisc's latex conversions to make a neater function to do it:
dvipng.dvi <-
function (object, file, ...)
{
cmd <- if (missing(file))
paste("dvipng -T tight", shQuote(object$file))
else paste("dvipng -T tight", "-o", file, shQuote(object$file))
invisible(sys(cmd))
}
And then you can do:
> tt # here is a table
y
x 1 2 3
1 9 12 11
2 18 9 10
3 10 7 14
> dvipng.dvi(dvi.latex(latex(tt)))
And that will produce a png file with a random name in the working directory. The -T tight option will crop all the whitespace from round it.
That's about as direct as I can think it possible.
Linux or Windows or Mac or Atari?
xtable provides the option to output either latex or html markup. You could put the html in directly.
Having said that I too would like to be able to go directly from knit or sweave to png or svg. I was trying to do this just last week. I am building an inkscape infographic (svg) and have been looking for a way to insert a linked image of a table that updates by running R code.
In initial testing I combined the use of xtable and Spacedman's (+1) code to get some nice png output (Ubuntu). -D option allows controlling of resolution.
I'm looking into a dvi->svg converter which is more like what I am after.
http://dvisvg.sourceforge.net/
dvipng.dvi <- function (object, file, res=600)
{
if (missing(file)){
invisible(sys(
paste("dvipng -T tight", "-D", res, shQuote(object$file)))
)
}
else{
invisible(sys(
paste("dvipng -T tight", "-D", res, "-o", file, shQuote(object$file)))
)
}
}
tt <- head(iris)
dvipng.dvi(dvi.latex(latex(xtable(tt))), file='iris.png')
With Spaceman's answer, I was able to come up with a solution that does not rely on latex from the Hmisc package as latex was causing some path problems for me:
table.png <- function(obj, name) {
first <- name
name <- paste(name,".tex",sep="")
sink(file=name)
cat('
\\documentclass{report}
\\usepackage[paperwidth=5.5in,paperheight=7in,noheadfoot,margin=0in]{geometry}
\\begin{document}\\pagestyle{empty}
')
print(xtable(obj))
cat('
\\end{document}
')
sink()
texi2dvi(file=name)
cmd <- paste("dvipng -T tight", shQuote(paste(first,".dvi",sep="")))
invisible(sys(cmd))
cleaner <- c(".tex",".aux",".log",".dvi")
invisible(file.remove(paste(first,cleaner,sep="")))
}
The kableExtra package allows to make nice and customized tables via LaTeX or HTML. It also has a function to export such standalone tables to, for example, PNG or PDF via webshot. Here is an example:
library(kableExtra)
knitr::kable(mtcars[1:6, 1:5], "latex", booktabs = TRUE, linesep = "") %>%
kable_styling(full_width = TRUE, font_size = 12) %>%
column_spec(1, width = "4cm") %>%
save_kable(file = "table.png")
I don't have a good answer that includes using R, but if you were desperate, I suppose a 'print screen' and a copy to Paint or other such program and finally saving it would at least get you the image in a storable format.
I've created 'step by step' user documentation this way when other options weren't available.