使用knitr以不同方式着色R输入和输出

时间:2014-11-20 01:24:40

标签: r latex knitr

我想将我的输入R代码打印/显示在浅灰色背景上,输出显示在白色背景上。因此,例如,如果我的.Rnw文件包含此块:

<<>>=
t.test(zinc~sex, data = zinc.df)
@

我希望用浅灰色背景渲染输入:

  

&GT; t.test(锌〜性别,数据=锌.df)

和要在白色背景上渲染的输出,例如

Welch双样本t检验

数据:按性别划分的锌

t = -15.08,df = 2678,p值< 2.2E-16

(故意截断输出,但你明白了)。看起来我可以用knitr主题做到这一点,但我不能很好地看到它。像许多人一样,我并不热衷于开始摆弄列表包。

3 个答案:

答案 0 :(得分:1)

您的问题最适合使用listings软件包,但不一定非常痛苦 - 这是一个示例(请注意backgroundcolor中的lstdefinestyle parm):

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{listings}
\usepackage{color}

%-- Define your colors, easy to look up
\definecolor{Rcodegreen}{rgb}{0,0.6,0}
\definecolor{Rcodegray}{rgb}{0.5,0.5,0.5}
\definecolor{Rcodepurple}{rgb}{0.58,0,0.82}
\definecolor{Rbackcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{customstyle}{
backgroundcolor=\color{Rbackcolour},   
commentstyle=\color{Rcodegreen},
keywordstyle=\color{Rmagenta},
numberstyle=\tiny\color{Rcodegray},
stringstyle=\color{Rcodepurple},
basicstyle=\footnotesize,
breakatwhitespace=false,         
breaklines=true,                 
captionpos=b,                    
keepspaces=true,                 
numbers=left,                    
numbersep=5pt,                  
showspaces=false,                
showstringspaces=false,
showtabs=false,                  
tabsize=2
}

\lstset{style=customstyle}

\title{Fooing with foo}

\begin{document}
\maketitle

<<tidy=TRUE,highlight=FALSE>>=
x <- "h3ll0 w0rld"
cat(x, "\n")

@

\end{document}

答案 1 :(得分:1)

这是我能做的最好的事情:

\documentclass[12pt,letterpaper,twoside]{book}  
\usepackage{inconsolata}
\usepackage{listings,color}

<<setup, include=FALSE>>=
options(width=60)
opts_chunk$set(fig.align='center', concordance=TRUE, fig.show='hold', size='footnotesize', prompt=FALSE, comment=NA, tidy=TRUE, results='markup', tidy.opts=list(width.cutoff=50), comment='#-#', highlight=TRUE)
opts_knit$set(concordance=TRUE,self.contained=FALSE)
color_block_output = function(x) {
function(x, options)  paste('\\begin{outputblock}',x,'\\end{outputblock}',sep="")
}
knit_hooks$set(output = color_block_output(''))
@

\lstnewenvironment{outputblock}{
\lstset{backgroundcolor=\color{white},
frame=single,
framerule=0pt,
basicstyle=\ttfamily,
columns=fullflexible}}{}

\begin{document}


<<test>>=
print('test')

(mat <- matrix(data=1:25,nrow=5,ncol=5)) 
@

\end{document}

结果将是:enter image description here

当没有输出(白色空间看起来有点奇怪)和尾随灰色空间时,我找不到解决方案。无论如何,这是一个开始,希望这会有所帮助。

答案 2 :(得分:1)

如果您仅使用Rnw和Latex,则可以使用块的background选项。但是,您需要两次编写块 (1)echo=TRUEeval=FALSEbackground='white'

<<echo=TRUE, eval=FALSE, background='white'>>=
@  

(2)echo=FALSEeval=TRUEbackground='yellow'

<<echo=FALSE, eval=TRUE, background='yellow'>>=
@    
相关问题