Skip to content

Instantly share code, notes, and snippets.

@seananderson
Last active December 29, 2015 03:39
Show Gist options
  • Save seananderson/7609459 to your computer and use it in GitHub Desktop.
Save seananderson/7609459 to your computer and use it in GitHub Desktop.
A script to stitch together figures, captions, and code from many people.
# Pull together figs, code, and captions into a knitr TeX document
# Sean Anderson November 24, 2013
# define some knitr chunks to print below:
opening <- "
<<>>=
"
closing <- "@\n"
preamble <- readLines("intro.Rnw")
postamble <- "\\end{document}"
this_filename <- "data-wrangling-figs"
this_filenameRnw <- paste0(this_filename, ".Rnw")
# get all the filenames:
.names <- list.files(pattern = "*\\.pdf$")
if(file.exists(paste0(this_filename, ".pdf")))
.names <- .names[-which(.names == paste0(this_filename, ".pdf"))]
filenames <- gsub("([a-z\\-]+)\\.pdf$", "\\1", .names)
# format names with a regular expression:
studentnames <- gsub("([a-z])([a-z]+)\\-([a-z])([a-z]+).pdf",
"\\U\\1\\L\\2 \\U\\3\\L\\4", .names, perl = TRUE)
lastnames <- gsub("([A-Za-z]+) ([A-Za-z]+)", "\\2", studentnames)
# sort the names:
filenames <- filenames[order(lastnames)]
studentnames <- studentnames[order(lastnames)]
# move "instructors" out of alphabetical order:
filenames <- filenames[-which(filenames %in% c("sean-anderson", "corey-phillis"))]
studentnames <- studentnames[-which(studentnames %in% c("Sean Anderson", "Corey Phillis"))]
filenames <- c(filenames, "sean-anderson", "corey-phillis")
studentnames <- c(studentnames, "Sean Anderson", "Corey Phillis")
# now start writing the .Rnw knitr file:
writeLines(preamble, con = this_filenameRnw)
# loop over the figures:
for (i in seq_len(length(filenames))) {
if(file.exists(paste0(filenames[i], ".txt"))) {
cap <- readLines(paste0(filenames[i], ".txt"))
} else {
cap <- ""
}
if(file.exists(paste0(filenames[i], ".R"))) {
code <- readLines(paste0(filenames[i], ".R"))
} else {
code <- ""
}
sink(this_filenameRnw, append = TRUE)
cat("
\\clearpage
")
cat(paste0("\\section*{", studentnames[i], "}
"))
cat(paste0("
\\begin{figure}[htp]
\\centering
\\includegraphics[width=4in]{", filenames[i], ".pdf}
\\caption{", cap, "}
\\end{figure}
"))
cat(paste0("<<", filenames[i],
", eval = FALSE, size=\"scriptsize\", tidy=FALSE>>=
"))
writeLines(code)
cat(closing)
sink()
}
sink(this_filenameRnw, append = TRUE)
cat(postamble)
sink()
# and process the document with knitr and TeX to create the PDF:
# you will need a LaTeX installation for this to work
knitr::knit(this_filenameRnw)
system(paste("xelatex", this_filename))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment