%Usage: knitr sweaveEx % rubber -d sweaveEx % (= pdflatex sweaveEx + bibtex sweaveEx sufficiently many times) % To get .R file: R CMD Stangle sweaveEx.Rnw = Stangle sweaveEx \documentclass{article} \usepackage{relsize,setspace} % used by latex(describe( )) \usepackage{url} % used in bibliography \usepackage[superscript,nomove]{cite} % use if \cite is used and superscripts wanted % Remove nomove if you want superscripts after punctuation in citations \usepackage{lscape} % for landscape mode tables \usepackage{calc,epic,color} % used for latex(..., dotchart=TRUE) \usepackage{moreverb} % handles verbatiminput % Macro changes: defines commands \cbstart* to use the changebar % package to draw vertical change bars for different edits (e.g. on % different days) having their own color/line thickness. A key is % generated in the text at the point at which \changes is called. % Change marking can be turned off without removing /cbstart* and % /cbend commands from the text. % % Usage: % \def\showchanges{1} or {0} to turn off change marking % \changes{suffix}{color}{thickness in pts}{description} % \changes{another suffix}{color}{thickness}{description} % . . . % Note that suffixes must contain only letters (single or multiple). % Suffixes are appended to \cbstart. \changes appears after % \begin{document}. % \usepackage[color]{changebar} \newcommand{\changes}[4]{% \ifnum\showchanges=1 \expandafter\newcommand\csname cbstart#1\endcsname{\cbstart[#3pt]\cbcolor{#2}}% \noindent Changes for #4 are marked by % \textcolor{#2}{\rule[0.05in]{.25in}{#3pt}} as a vertical line in the right margin\\ \else \expandafter\newcommand\csname cbstart#1\endcsname{}% \def\cbend{} \fi } \textwidth 6.75in % set dimensions before fancyhdr \textheight 9.25in \topmargin -.875in \oddsidemargin -.125in \evensidemargin -.125in \usepackage{fancyhdr} % this and next line are for fancy headers/footers \pagestyle{fancy} \newcommand{\bc}{\begin{center}} % abbreviate \newcommand{\ec}{\end{center}} \newcommand{\code}[1]{{\smaller\texttt{#1}}} \newcommand{\R}{{\normalfont\textsf{R}}{}} % Define the following only if you put figures in a figure environment %\fg{basefilename}{label}{caption} \newcommand{\fg}[3]{\begin{figure}[htbp]% \leavevmode\centerline{\includegraphics{graphics/#1}}% \caption{\smaller #3}\label{#2}\end{figure}} \usepackage{Sweavel} % Uncomment some of the following to use some alternatives: % \def\Sweavesize{\normalsize} (changes size of typeset R code and output) % \def\Rcolor{\color{black}} % \def\Routcolor{\color{green}} % \def\Rcommentcolor{\color{red}} % To change background color or R code and/or output, use e.g.: % \def\Rbackground{\color{white}} % \def\Routbackground{\color{white}} % To use rgb specifications use \color[rgb]{ , , } % To use gray scale use e.g. \color[gray]{0.5} % If you change any of these after the first chunk is produced, the % changes will have effect only for the next chunk. <>= knitrSet(w=5, h=3.5) # function is defined in my .Rprofile # To omit code and its output throughout, use # knitrSet(echo=FALSE, results='hide'} @ %\SweaveOpts{prefix.string=graphics/plot, eps = FALSE, pdf = TRUE} \title{Example Enhanced Report} \author{Frank E Harrell Jr\\\smaller Department of Biostatistics\\\smaller Vanderbilt University School of Medicine} \begin{document} \maketitle \def\showchanges{1} \changes{a}{blue}{1}{2014-10-02} \changes{b}{red}{2}{2014-10-04} % Use the following 3 lines for long reports needing navigation %\tableofcontents %\listoftables %\listoffigures % not used unless figure environments used \section{Descriptive Statistics}\label{descStats} <>= require(rms) # Get access to rms and Hmisc packages getHdata(support) # Use Hmisc/getHdata to get dataset from VU DataSets wiki d <- subset(support, select=c(age,sex,race,edu,income,hospdead,slos,dzgroup, meanbp,hrt)) latex(describe(d), file='') @ Race is reduced to three levels (white, black, OTHER) because of low frequencies in other levels (minimum relative frequency set to 0.05). <<>>= d <- transform(d, race = combine.levels(race, minlev = 0.05)) @ \cbstarta Summaries of variables stratified by sex are below. <>= latex(summaryM(age + race + edu + income + slos + dzgroup + meanbp + hrt ~ sex, data=d, test=TRUE), npct='both', file='', landscape=TRUE, round=1) @ \cbend \section{Redundancy Analysis and Variable Interrelationships} \bc % Note: giving a chunk name to each code chunk that produces a figure % makes it easy to know which plots to send to a collaborator, and % will not allow numbered orphan plots to be left when code chunks are % inserted into the file. The default in knitr is for plots to be % numbered by the chunks producing them. \cbstartb <>= v <- varclus(~., data=d) plot(v) redun(~ age + sex + race + edu + income + dzgroup + meanbp + hrt, data=d) # Alternative: redun(~., data=subset(d, select=-c(hospdead,slos))) @ \ec Note that the clustering of black with white is not interesting; this just means that these are mutually exclusive higher frequency categories, causing them to be negatively correlated. \cbend \section{Logistic Regression Model} Here we fit a tentative binary logistic regression model. The coefficients are not very useful so they are not printed (\dots is printed in their place). Artificially create more missing data so that a dot chart showing frequencies of missings will be printed when the \code{latex} version of the output appears later. <>= dd <- datadist(d); options(datadist='dd') d$age[1:10] <- d$meanbp[1:13] <- d$hospdead[1:7] <- NA f <- lrm(hospdead ~ rcs(age,4) + sex + race + dzgroup + rcs(meanbp,5), data=d) # see Section (*\ref{descStats}*) for descriptive statistics f <>= z <- capture.output( { <> } ) prselect(z, 'S.E.') # keep only summary stats; or: # prselect(z, stop='S.E.', j=-1) # keep only coefficients @ Better: Directly output model statistics as \LaTeX\ markup and easily suppress coefficients. <>= print(f, latex=TRUE, coefs=FALSE) @ The mean arterial blood pressure effect is shown below, on the probability scale. \textbf{Note}: \code{knitr} was told to automatically use a \LaTeX\ floating \code{figure} environment since a caption was given. <<>= p <- Predict(f, meanbp, fun=plogis) <>= plot(p, ylab='Prob[hospital death]', adj.subtitle=FALSE) # Figure (*\ref{fig:meanbp}*) <>= latex(anova(f), where='h', file='') # can also try where='htbp' @ The likelihood ratio $\chi^{2}$ statistic is \Sexpr{round(f$stats['Model L.R.'],2)} on \Sexpr{f$stats['d.f.']} d.f. The fitted model in algebraic form is found below. <>= latex(f, file='') @ \section{Computing Environment} These analyses were done using the following versions of \R\cite{Rsystem}, the operating system, and add-on packages \code{Hmisc}\cite{Hmisc}, \code{rms}\cite{rrms}, and others: <>= toLatex(sessionInfo(), locale=FALSE) @ % Note: Rsystem reference is defined inside feh.bib. It is a slightly % edited version of the output of citation(). \bibliography{/home/harrelfe/bib/harrelfe.bib} \bibliographystyle{unsrt} % Use \bibliographystyle{abbrv} if want references alphabetized \section{Source Code for This Report} \verbatimtabinput{sweaveEx.Rnw} \section{\code{Sweavel.sty}} \verbatimtabinput{/home/harrelfe/doc/latex/texinput/Sweavel.sty} \end{document}