Include LaTeX code from R objects into markdown - r

I am writing up a report where the output gets pushed to a xlsx document via library(xlsx). This data then feeds into a table especially formatted with LaTeX code that formats the output:
```{r import_results, echo = F}
if(!file.exists("Analysis/results.xlsx")){
wb <- xlsx::createWorkbook(type = "xlsx")
sheets <- xlsx::createSheet(wb, "data")
}else{
wb <- loadWorkbook("Analysis/results.xlsx")
sheets <- removeSheet(wb, "data")
sheets <- xlsx::createSheet(wb, "data")
}
getSheets(wb)
addDataFrame(sheet = sheets, x = Results1)
addDataFrame(sheet = sheets, x = Results2, startRow = nrow(Results1)+2)
addDataFrame(sheet = sheets, x = Results3, startRow = nrow(Results1)+ nrow(Results2) + 4)
xlsx::saveWorkbook(wb, "Analysis/results.xlsx")
}
After writing to sheet that table data is linked to, I read it back into R, now with all the LaTeX in the cells and in essence I want to cat results so they are LaTeX code, but it prints the data.frame as a long string when I knit:
```{r, echo = F, results='asis'}
wb <- read.xlsx("Analysis/results.xlsx", sheetName = "import", header=F)
row.names(wb) <-NULL
wb
```
What is the appropriate way to automate this cross platform integration?

I got the example to work in a very "simplistic" manner. Although I dont think its the cleanest code out there, it does work for what I need it to do:
library(dplyr)
library(xlsx)
wb <- read.xlsx("Analysis/results.xlsx", sheetName = "import", header=F, stringsAsFactors = F)
wb <- mutate_each(wb, funs(replace(., which(is.na(.)), "")))
```{r, echo = F, results = 'asis'}
for(i in 1:nrow(wb)){
cat(unlist(wb[i,]),"\n")
}
```

Related

Save interactive Plotly in PDF or EPS in R

library(tidyverse)
library(easyalluvial) # https://github.com/erblast/easyalluvial
library(parcats) # https://github.com/erblast/parcats
# My data
knitr::kable(head(mtcars2))
# My Alluvial
MyAlluvial <- alluvial_wide(data = mtcars2,
max_variables = 5,
fill_by = 'first_variable')
# My Nice alluvial
p <- parcats(MyAlluvial, marginal_histograms = FALSE, data = mtcars2)
p
# Saving PDF
pdf("/Users/Master/Downloads/MyAlluvial.pdf")
p
dev.off()
I'm able to save the plot as png/jpg using RStudio GUI, but I cannot save it in a vector format (neither pdf nor eps).
As far as I known, interactive plot was generated using Plotly.
I can save printing a PDF from the browser but I don't like this!!
I was able to save your graph in a PDF file with the following code :
library(rmarkdown)
library(pagedown)
vector_RMD_Content <- c(
'---',
'title: "Untitled"',
'output: html_document',
'---',
'```{r setup, include=FALSE}',
'knitr::opts_chunk$set(echo = TRUE)',
'```',
'```{r cars}',
'library(tidyverse)',
'library(easyalluvial)',
'library(parcats)',
"MyAlluvial <- alluvial_wide(data = mtcars2, max_variables = 5, fill_by = 'first_variable')",
'p <- parcats(MyAlluvial, marginal_histograms = FALSE, data = mtcars2)',
'p',
'```')
zzfil <- tempfile(fileext = ".Rmd")
writeLines(text = vector_RMD_Content, con = zzfil)
render(input = zzfil,
output_file = "C:/stackoverflow.html")
chrome_print("C:/stackoverflow.html",
output = "C:/testpdf2.pdf")
A html file with your graph is generated with Rmarkdown. After, the HTML file is printed to PDF with the R function chrome_print of the R package pagedown.

How to print an html table to pdf?

Consider this simple example
library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:4]
# HTML table
kable(dt, format = "html", caption = "Demo Table") %>%
kable_styling(bootstrap_options = "striped",
full_width = F) %>%
add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
add_footnote(c("table footnote"))
Here I want a very simple thing. To print this table in a pdf (possibly in a pipe-able way). I want the table to look exactly like this.
I know this is html, but arent we able to print html pages to pdf in chrome? There has to be a way (I hope). I do not want to deal with latex and I do not want to create an rnotebook document. The rendering has to come from my bare .R script. Is that impossible?
Any ideas?
Thanks!
Here is a solution to part of your problem of generating a table in pdf form. You will need to tweak the styling of your table in xtable in order to get the zebra stripe you want and merged columns. Generally speaking conversion from html to pdf is not so straightforward, so a better solution is to use LaTeX to generate your table in the first place (I know you didn't want LaTeX, but at least this is compiled to pdf with R and xtable does the hard work):
library(xtable)
dt <- mtcars[1:5, 1:4]
filename <- tempfile(fileext = ".tex")
capture.output(print(xtable(dt)), file = filename)
foo <- readLines(filename)
writeLines(c("\\documentclass[hidelinks]{article}",
"\\begin{document}",
foo,
"\\end{document}"),
con = filename)
tools::texi2dvi(filename, pdf = TRUE)
You should have a look at https://cran.r-project.org/web/packages/xtable/vignettes/xtableGallery.pdf to get your styling the way you want it. Good luck.
Edit:
Seems you can use kabelExtra too:
library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:4]
# LaTeX table
a <- kable(dt, format = "latex", caption = "Demo Table") %>%
kable_styling(bootstrap_options = "striped",
full_width = F) %>%
add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
add_footnote(c("table footnote"))
filename <- tempfile(fileext = ".tex")
capture.output(a, file = filename)
foo <- readLines(filename)
writeLines(c("\\documentclass[hidelinks]{article}",
"\\begin{document}",
foo,
"\\end{document}"),
con = filename)
tools::texi2dvi(filename, pdf = TRUE)

How to show and run code but don't print results in Rmarkdown knitr

When I knit the following code chunk in Rmarkdown it will print out the results as well. I just want to run and show the code. In other code chunks in the same .Rmd file this knitr syntax works...
```{r import, results = "hide"}
gs_ls()
df <- gs_title("worlds-view-of-America")
confInPres <- df %>% gs_read(ws = "Sheet1", range = cell_rows(1:38))
colnames(confInPres) <- paste("year", colnames(confInPres), sep = "_")
colnames(confInPres)[1] <- "Country"
confInTrump <- select(confInPres, Country, year_2017)
favUS <- df %>% gs_read(ws = "Sheet2", range = cell_rows(1:38))
```
Take a look here.
If you want to show the code, use echo=TRUE.

R language/reporteRs loop to write multiple docx

I'm trying (as hard as i can) to create a script that will generate formatted word documents from plain text files using R language and reporteRs.
To extract text from one txt i'm using this code found on this thread Dealing with readLines() function in R :
fileName <- "C:/MyFolder/TEXT_TO_BE_PROCESSED.txt"
con <- file(fileName,open="r")
line <- readLines(con)
close(con)
Then add the extracted text to docx with this :
doc <- docx(template="temp.docx")
Next, adding the title (first line of the txt file)
doc <- addParagraph( doc, value = line[1], bookmark = "titre", stylename = "Titre")
then the body of the txt file
doc <- addParagraph( doc, value = line[2:length(line)], value = line[2:55], stylename = "Contenu")
Finally I create the docx
writeDoc(doc, file = "output-file.docx")
I want to be able to create a loop so I can generate multiple docx from multiple txt files. I will really appreciate your help
You can do something like this with lapply
myFiles <- c("C:/MyFolder/TEXT_TO_BE_PROCESSED.txt", "C:/MyFolder/TEXT_TO_BE_PROCESSED2.txt") # or use list.files()
lapply(myFiles, function(fileName){
con <- file(fileName,open="r")
line <- readLines(con) # you could just call readLines(fileName)
close(con)
doc <- docx(template="temp.docx")
doc <- addParagraph( doc, value = line[1], bookmark = "titre", stylename = "Titre")
doc <- addParagraph( doc, value = line[2:length(line)], value = line[2:55], stylename = "Contenu")
writeDoc(doc, file = paste0(fileName, "out.docx"))
})
The solution :
myFiles <- list.files()
lapply(myFiles, function(fileName){
line <- readLines(fileName)
doc <- docx(template="temp.docx")
doc <- addParagraph( doc, value = line[1], bookmark = "titre",
stylename = "Titre ยป)
doc <- addParagraph( doc, value = line[2:length(line)], stylename = "Contenu")
writeDoc(doc, file = paste0(fileName, ".docx"))
})
Thank you again Richard

Function in R saving in *.xls

I created a program that breaks a database in several other banks. But in this program I save this several banks in txt so now I'd like save in xls, but I don't know how.
I tried for (nm in Nms) write.table(Res[[nm]], paste(nm, 'xls', sep='.'), sep="\t",dec=",",col.names=TRUE, row.names=FALSE, quote=TRUE, na="NA")
but it did not work
decup <- function(dados,var){
require(gdata)
dados <- read.xls("dados.xls")
attach(dados)
Res = split(dados, var)
for (nm in Nms) write.table(Res[[nm]], file=paste(nm, 'txt', sep='.'))
for (nm in Nms) zip(paste(nm,'zip',sep='.'),paste(nm,'xls',sep='.'), zip = Sys.getenv("R_ZIPCMD", "zip"))
}
You can use library XLConnect to read/write .xlsx files and
writeWorksheet let's you save the your data.frames:
library(XLConnect)
## open workbook or create it if doesn't exist
wb <- loadWorkbook("writeWorksheet.xlsx", create = TRUE)
## for each data.frame create a sheet with its data
lapply(seq_along(Res), function(x)
createSheet(wb, name = paste0("sheet",x))
writeWorksheet(wb, Res[[x]], sheet = paste0("sheet",x), startRow = 4, startCol = 2)
}
# Save workbook (this actually writes the file to disk)
saveWorkbook(wb)
EDIT to save a data.frame by workbook you do this :
lapply(seq_along(Res), function(x){
wb <- loadWorkbook(paste0("database",x), create = TRUE)
createSheet(wb, name ='sheet1' )
writeWorksheet(wb, Res[[x]], sheet = 'sheet1', startRow = 4, startCol = 2)
saveWorkbook(wb)
})

Resources