Skip to content

Commit

Permalink
moved from svn to git
Browse files Browse the repository at this point in the history
  • Loading branch information
tscheypidi committed Jan 15, 2018
0 parents commit ac39bb5
Show file tree
Hide file tree
Showing 18 changed files with 752 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
^.*\.Rproj$
^\.Rproj\.user$
29 changes: 29 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# History files
.Rhistory
.Rapp.history

# Session Data files
.RData
# Help files (because they will be created automatically by roxygen)
*.Rd
# Example code in package build process
*-Ex.R
# Output files from R CMD build
/*.tar.gz
# Output files from R CMD check
/*.Rcheck/
# RStudio files
.Rproj.user/
# produced vignettes
vignettes/*.html
vignettes/*.pdf
# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3
.httr-oauth
# knitr and R markdown default cache directories
/*_cache/
/cache/
# Temporary files created by R markdown
*.utf8.md
*.knit.md
.Rproj.user
inst/doc
15 changes: 15 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Package: lusweave
Type: Package
Title: Landuse Sweave Utilities
Version: 1.43.4
Date: 2017-11-29
Author: Markus Bonsch, Jan Philipp Dietrich, Florian Humpenoeder
Maintainer: Jan Philipp Dietrich <dietrich@pik-potsdam.de>
Description: Set of tools which simplify the usage of SWeave in R and allow to easily create PDF files based on R data.
Depends: R(>= 2.10.0), methods
Imports: xtable,
knitr,
utils
License: BSD_2_clause + file LICENSE
LazyData: no
RoxygenNote: 6.0.1
2 changes: 2 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
YEAR: 2016
COPYRIGHT HOLDER: Potsdam Institute for Climate Impact Research (PIK)
13 changes: 13 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Generated by roxygen2: do not edit by hand

export(swR)
export(swclose)
export(swfigure)
export(swlatex)
export(swopen)
export(swtable)
importFrom(methods,is)
importFrom(methods,new)
importFrom(utils,Sweave)
importFrom(utils,data)
importFrom(xtable,xtable)
25 changes: 25 additions & 0 deletions R/Sweave.sty
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{Sweave}{}
\RequirePackage{ifthen}
\newboolean{Sweave@gin}
\setboolean{Sweave@gin}{true}
\newboolean{Sweave@ae}
\setboolean{Sweave@ae}{true}
\DeclareOption{nogin}{\setboolean{Sweave@gin}{false}}
\DeclareOption{noae}{\setboolean{Sweave@ae}{false}}
\ProcessOptions
\RequirePackage{graphicx,fancyvrb}
\ifthenelse{\boolean{Sweave@gin}}{\setkeys{Gin}{width=\textwidth}}{}%
\ifthenelse{\boolean{Sweave@ae}}{%
\RequirePackage[T1]{fontenc}
\RequirePackage{ae}
}{}%
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{fontsize=\small,xleftmargin=0mm,xrightmargin=0mm}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}
\newenvironment{Schunk}{}{}
\newcommand{\Sconcordance}[1]{%
\ifx\pdfoutput\undefined%
\csname newcount\endcsname\pdfoutput\fi%
\ifcase\pdfoutput\special{#1}%
\else\immediate\pdfobj{#1}\fi}
9 changes: 9 additions & 0 deletions R/lusweavedata.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#' lusweavedata
#' @description General lusweave-dataset
#' @aliases lusweavedata
#' @details Pleasde do not directly acces that data. It should be only used by library functions.
#' @author Jan Philipp Dietrich
#' @name lusweavedata
#'

NULL
87 changes: 87 additions & 0 deletions R/swR.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#' swR
#'
#' Function to write R code to a \code{"\linkS4class{swStream}"} object.
#'
#' Method designed to write the output of R commands to a swStream object,
#' taking care that it is correctly embedded. As \code{func} argument, you can
#' pass either the function itself or its name as a string. User defined
#' functions will only work with option one, two is only for back
#' compatibility.
#'
#' @usage swR(stream,func,...,option = "echo=FALSE")
#' @param stream The \code{swStream} object to be modified.
#' @param func The R command, that shall be ecexuted. Can be specified as a
#' string for back compatibility
#' @param ... Additional parameters passed to the function.
#' @param option Formatting options.
#' @return No return value.
#' @author Markus Bonsch
#' @export
#' @seealso
#' \code{"\linkS4class{swStream}"},\code{\link{swopen}},\code{\link{swclose}},\code{\link{swlatex}},\code{\link{swtable}},\code{\link{swfigure}}
#' @examples
#' \dontrun{
#' test<-swopen(outfile="test.pdf")
#' swR(test,print,ls)
#' swR(test,print,"bla_blubb")
#' x<-c(1,2,3)
#' swR(test,print,paste(x,"bla"))
#' swclose(test)
#' # Only for back compatibility
#' swR(test,"print","bla_blubb")
#' }
#'
#'
# write R code to a sweaveStream object:
# define the function and its arguments
# <<"option">>=
# "func(...)"
# @
swR<-function(stream,func,...,option = "echo=FALSE"){
envir<-stream
stream<-get("stream",envir=envir,inherits=FALSE)
orig_stream <- stream
stufftowrite <- NULL
if(class(stream)=="swStream"){
tryCatch({
pos<-length(stream@functions)
args<-list(...)

#save func (necessary in case, it is user defined)
if(is.function(func)){
stream@functions[[pos+1]]<-func
} else{ #needed for back compatibility
stream@functions[[pos+1]]<-get(func,pos=1,inherits=TRUE)
}
#paste the command
stufftowrite<-paste("stream@functions[[",pos+1,"]](",sep="")
if(length(args)>0){
#save all arguments as a list in the objects slot of the stream object.
stream@arguments[[pos+1]]<-args
#paste the arguments in the appropriate format
for(i in 1:length(args)){
if(any(names(args)!="")){
if(names(args)[i]!=""){
stufftowrite<-paste(stufftowrite,names(stream@arguments[[pos+1]])[i],"=","stream@arguments[[",pos+1,"]][[",i,"]],",sep="")
}else{
stufftowrite<-paste(stufftowrite,"stream@arguments[[",pos+1,"]][[",i,"]],",sep="")
}
}else{
stufftowrite<-paste(stufftowrite,"stream@arguments[[",pos+1,"]][[",i,"]],",sep="")
}
}
}
#remove last comma
if(substr(stufftowrite,nchar(stufftowrite),nchar(stufftowrite))==",") stufftowrite<-substr(stufftowrite,1,nchar(stufftowrite)-1)
#add options and closing bracket
stufftowrite<-paste(stufftowrite,")",sep="")
stufftowrite<-c(paste("<<",option,">>=",sep=""),stufftowrite,"@")
}, error=function(e){warning("Error occurred in swR, stream will be set back to previous value.\n Error message: ",e$message,call. = FALSE);stream <- orig_stream})
# Save the updated stream object
assign("stream",stream,envir = envir)
swlatex(envir,stufftowrite)
}else{
stop("Input is not a sweaveStream!")
}
}

25 changes: 25 additions & 0 deletions R/swStream-class.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#' Class "swStream" ~~~
#'
#' The swStream class provides an interface to the Sweave method and allows for
#' easy creation of pdf's from R output.
#'
#' The Sweave method is an interface between R and LaTeX. It processes .Rnw
#' files, that can contain LaTeX code as well as R code into proper .tex files,
#' replacing the R commands by their output. See
#' \code{http://www.stat.uni-muenchen.de/~leisch/Sweave/} for details.\cr An
#' additional style file is needed to compile the .tex file into a pdf.
#'
#' @name swStream-class
#' @docType class
#' @section Objects from the Class: Objects can be created by calls of the form
#' \code{new("swStream", name,folder, content, Sweave.sty, arguments,
#' functions, auxfiles, envir)}.
#' @author Markus Bonsch
#' @seealso
#' \code{\link{swopen}},\code{\link{swclose}},\code{\link{swlatex}},\code{\link{swR}},\code{\link{swtable}},\code{\link{swfigure}}
#' @keywords classes
#' @examples
#' \dontrun{
#' showClass("swStream")
#' }
setClass("swStream",representation(name = "character",content = "vector",Sweave.sty="vector",functions="list",arguments="list",auxfiles="vector",envir="environment"),prototype = list(name = "",content = c("",""),Sweave.sty=c("",""),functions=list(),arguments=list(),auxfiles=c("",""),envir=.GlobalEnv))
118 changes: 118 additions & 0 deletions R/swclose.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#' Close a swStream
#'
#' Function to create a pdf from a \code{"\linkS4class{swStream}"} object
#'
#' Creates a pdf with of the name specified in \code{stream@name}, with the
#' content specified in \code{stream@content}, using \code{stream@Sweave.sty}
#' as the style file.
#'
#' @usage swclose(stream,outfile="",latexpath="",clean_output=TRUE,
#' engine="knitr", save_stream=TRUE, knitquiet = FALSE)
#' @param stream The \code{swStream} object to be processed.
#' @param outfile Name of the pdf to be produced. Overwrites the name given in
#' swopen
#' @param latexpath Path of the LaTeX distribution (only necessary if not part
#' of the PATH variable).
#' @param clean_output If true, all auxiliary files will be deleted. If False,
#' they remain, including each plot in its own pdf.
#' @param engine Engine to use for conversion. Currently available: Sweave and
#' knitr.
#' @param save_stream If true (default) stream is saved to .rda file.
#' @param knitquiet If false (default) progressbar and messages are printed
#' otherwise suppressed.
#' @return No return value.
#' @author Markus Bonsch, David Klein
#' @export
#' @seealso
#' \code{"\linkS4class{swStream}"},\code{\link{swopen}},\code{\link{swlatex}},\code{\link{swR}},\code{\link{swtable}},\code{\link{swfigure}}
#' @examples
#' \dontrun{
#' test<-swopen(outfile="test.pdf")
#' swlatex(test,"tttteeeesssstttt")
#' swclose(test)
#' #Change the name
#' swclose(test,outfile="test_2.pdf")
#' }
#'
#method to create a pdf from the swStream object
swclose<-function(stream,outfile="",latexpath="",clean_output=TRUE, engine="knitr", save_stream=TRUE, knitquiet = FALSE){

#Write "content" (extended by "\end{document}")to an Rnw file,
#sweave this file and produce the pdf from the .tex file. Then delete the sweaveStream
if(is.environment(stream)) {
envir<-stream
stream<-get("stream",envir=envir,inherits=FALSE)
} else {
envir <- new.env()
assign("stream",stream,envir=envir)
}
if(class(stream)=="swStream"){
#update the name if necessary
if(outfile!=""){
if(length(strsplit(outfile,split="/")[[1]])>1){
tmp<-strsplit(outfile,split="/")[[1]]
outfile<-tmp[length(tmp)]
folder<-paste(tmp[1:(length(tmp)-1)],collapse="/")
} else{
folder<-""
}
outfile<-strsplit(outfile,".pdf", fixed=TRUE)[[1]]
outfile<-gsub("\\.","-_-_-",outfile)
stream@auxfiles<-gsub(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],strsplit(outfile,".pdf", fixed=TRUE)[[1]],stream@auxfiles)
stream@name<-outfile
stream@folder<-folder
assign("stream",stream,envir = envir)
}

stream@content<-c(stream@content,"\\end{document}")

this_dir<-getwd()
if(stream@folder!="") setwd(stream@folder)

if(save_stream) save(stream,file=paste0(stream@name,".rda"),compress = "xz")

writeLines(stream@content,paste(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],".Rnw",sep=""))
#create the style file if no external one is specified
writeLines(stream@Sweave.sty,"Sweave.sty")
#execute the Sweave routine which executes the R code in the Rnw file and produces a tex file


#Attach the stream to the global environment because this is where Sweave does the evaluation
globalenv = .GlobalEnv
tmp<-try(get("stream",envir=globalenv),silent=TRUE)
assign("stream",stream,envir=globalenv)
#now run Sweave or knitr
rnwfile <- paste(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],".Rnw",sep="")
if(engine=="Sweave") {
Sweave(rnwfile,encoding="bytes")
} else if(engine=="knitr"){
if (!requireNamespace("knitr", quietly = TRUE)) stop("The package knitr is not available!")
knitr::Sweave2knitr(rnwfile,output = rnwfile)
suppressWarnings(knitr::knit(rnwfile,quiet = knitquiet))
} else {
stop("Unknown engine ",engine)
}

#restore stream object in the global environment
if(!is(tmp,"try-error")) assign("stream",tmp,envir=globalenv)

#check for command pdflatex and change latexpath in the case that it cannot be found
latexpaths <- c(latexpath,"/iplex/01/sys/applications/texlive/bin/x86_64-linux/","","not found")
for(latexpath in latexpaths) {
if(Sys.which(paste0(latexpath,"pdflatex"))!="") break
}
if(latexpath=="not found") stop("Executable pdflatex could not be found. Please check your latexpath setting")
#compile to pdf, needed two times for generation of table of contents
for(i in 1:2) {
error_code<-suppressWarnings(system(paste0(latexpath,"pdflatex --interaction=nonstopmode ",paste0(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],".tex")),intern=TRUE))
}
if(!is.null(attr(error_code,"status"))) warning("Execution of pdflatex reported an error (code ",attr(error_code,"status"),") please check the corresponding log file for further information.")
file.rename(paste(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],".pdf",sep=""),paste(gsub("-_-_-","\\.",strsplit(stream@name,".pdf", fixed=TRUE)[[1]]),".pdf",sep=""))
file.rename(paste(strsplit(stream@name,".pdf", fixed=TRUE)[[1]],".log",sep=""),paste(gsub("-_-_-","\\.",strsplit(stream@name,".pdf", fixed=TRUE)[[1]]),".log",sep=""))
#remove unnecessary compilation files
if(clean_output==TRUE) log<-suppressWarnings(file.remove(stream@auxfiles))
setwd(this_dir)
}else{
stop("Input is not a sweaveStream!")
}
}
Loading

0 comments on commit ac39bb5

Please sign in to comment.