2012-08-27 1 views
15

私はknitrでRでレポートを書いています。私はxtable()を使ってレポート内のテーブルを生成しています。私のテーブルの1つは、負の数と正の数の両方を含んでいます。私は負の数の色を赤に変えたいと思います。どうやってやるの? 明らかに、xtableが生成するラテックスコードを変更するのが簡単な解決策ですが、数値が新しいデータセットで変更される可能性があり、手動で色を設定したくないという自動レポートがあることに注意してください。xtable()で生成されたテーブルの負の数の色を赤に変更しますか?

\documentclass{article} 
\begin{document} 
<<simpleExamp, results=tex, echo=FALSE>>= 
library(knitr) 
library(xtable) 
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2) 
xtable(testMatrix) 
@ 
\end{document} 

どのように私は負の数赤い作ることができます:ここでは

は簡単なコードですか? ありがとうございます。

答えて

24

capture.output()を使用して、print.xtable()への(暗黙の)呼び出しによって印刷された行をキャプチャできます。次に、\textcolor{red}{}で各負の数値を囲むパターンと置換を使用して、gsub()を出力に適用します。最後にsep="\n"cat()を使用して、変更された行を*.texファイルに書き出します。

\documentclass{article} 
\begin{document} 
<<simpleExamp, results="asis", echo=FALSE>>= 
library(knitr) 
library(xtable) 
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2) 
## I added the following three lines 
xt <- capture.output(xtable(testMatrix)) 
xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt) 
cat(xt_mod, sep="\n") 
@ 
\end{document} 


編集

(Iはknitr 'が好む' は、それがより迅速にプロセスれる、results="asis"results=texを置き換えることにも注意してください。):得られた画像を追加表。 (SO対応形でそれを取得も以下に含まれるコードにいくつかの調整が必要であった。)

enter image description here

\documentclass{standalone} 
\renewenvironment{table}{}{}% Ignore `table` environment in standalone mode. 
\begin{document} 
<<simpleExamp, results="asis", echo=FALSE>>= 
library(knitr) 
library(xtable) 
cat("\\Huge\n\n") 
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2) 
## I added the following three lines 
xt <- capture.output(print.xtable(xtable(testMatrix), table.placement=NULL)) 
xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt) 
cat(xt_mod, sep="\n") 
@ 
\end{document} 
+3

ワンダフル。非常に良い答え。あなたの答えは、私がしばらく考えてきた他の多くの問題に対して、私に良いアイデアを与えました。 – Sam

+0

@Sepehr - 'capture.output()'をキービットで使用していましたか? –

+0

でした。私はその機能が存在するのか知らなかった。これでテーブルを簡単にカスタマイズできます。再度、あなたの助けをありがとう。 – Sam

3

テーブルを着色するために少しTWEAKとジョシュオブライエンの回答をコピーし小数点付き:

\documentclass{article} 
\begin{document} 
<<simpleExamp, results="asis", echo=FALSE>>= 
library(knitr) 
library(xtable) 
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)*1.1 
## I added the following three lines 
xt <- capture.output(xtable(testMatrix)) 
xt_mod <- gsub("(\\s|^)(-\\d\\.\\d*)", "\\1\\\\textcolor{red}{\\2}", xt) 
cat(xt_mod, sep="\n") 
@ 
\end{document} 
関連する問題