我正在尝试将带有负数的表导出到乳胶。我想这样做print(xtable())
以访问所有打印选项。
目前,我找到的唯一解决方案是:(以前面的例子为例)
library(xtable)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
xt <- capture.output(xtable(testMatrix))
sink(paste(file.name, ".tex", sep = "", collapse = NULL))
cat(gsub("(\\s|^)(-\\d\\.\\d*)", "\\1\\\\textcolor{red}{\\2}", xt), sep="\n")
sink()
它的工作原理,但我需要修改一些信息直接无法访问的xtable
,如:include.rownames
,math.style.exponents
或caption.placement
。最好的方法是直接使用print
和导出负十进制数的简单方法xtable
。任何想法?
你需要做两件事:
capture.output(print(xtable(testMatrix)))
代替capture.output(xtable(testMatrix))
。然后就可以使用print.xtable()
.观察:
library(xtable)
set.seed(123)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
xt <- capture.output(print(xtable(testMatrix))) # Notice use of print()
negative_number_pattern <- "(\\s|^)(-\\d+\\.*\\d*)" # Notice changed pattern
cat(gsub(negative_number_pattern, "\\1\\\\textcolor{red}{\\2}", xt), sep="\n")
% latex table generated in R 3.6.0 by xtable 1.8-4 package
% Mon May 13 08:02:53 2019
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
\hline
& 1 & 2 \\
\hline
1 & 4 & \textcolor{red}{-9} \\
2 & 8 & \textcolor{red}{-5} \\
3 & 3 & 0 \\
4 & \textcolor{red}{-8} & \textcolor{red}{-6} \\
5 & \textcolor{red}{-1} & \textcolor{red}{-7} \\
\hline
\end{tabular}
\end{table}
xt <- capture.output(print(xtable(testMatrix), include.rownames = FALSE))
cat(gsub(negative_number_pattern, "\\1\\\\textcolor{red}{\\2}", xt), sep="\n")
% latex table generated in R 3.6.0 by xtable 1.8-4 package
% Mon May 13 08:02:53 2019
\begin{table}[ht]
\centering
\begin{tabular}{rr}
\hline
1 & 2 \\
\hline
4 & \textcolor{red}{-9} \\
8 & \textcolor{red}{-5} \\
3 & 0 \\
\textcolor{red}{-8} & \textcolor{red}{-6} \\
\textcolor{red}{-1} & \textcolor{red}{-7} \\
\hline
\end{tabular}
\end{table}
如您所见,通过使用print()
,我们能够使用您正在寻找的选项(这里我演示了更改include.rownames
为FALSE
)。
如果要filename.tex
直接从 R 命令打印表,可以使用cat()
'sfile
参数。来自help("cat")
:
用法
cat(... , file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)参数
... R 对象(有关允许的对象类型,请参阅“详细信息”)。file 一个连接,或命名要打印到的文件的字符串。如果是“”(默认值),则 cat 打印到标准输出连接,控制台除非被接收器重定向。如果它是“|cmd”,则通过打开管道连接将输出通过管道传送到“cmd”给出的命令。
所以这:
library(xtable)
set.seed(123)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
xt <- capture.output(print(xtable(testMatrix))) # Notice use of print()
negative_number_pattern <- "(\\s|^)(-\\d+\\.*\\d*)" # Notice changed pattern
cat(gsub(negative_number_pattern, "\\1\\\\textcolor{red}{\\2}", xt), sep="\n",
file = "filename.tex")
导致以下内容filename.tex
:
% latex table generated in R 3.6.0 by xtable 1.8-4 package
% Mon May 13 08:53:44 2019
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
\hline
& 1 & 2 \\
\hline
1 & 4 & \textcolor{red}{-9} \\
2 & 8 & \textcolor{red}{-5} \\
3 & 3 & 0 \\
4 & \textcolor{red}{-8} & \textcolor{red}{-6} \\
5 & \textcolor{red}{-1} & \textcolor{red}{-7} \\
\hline
\end{tabular}
\end{table}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句