开发者

using gsub to modify output of xtable command

my.mat <- cbind(1:5, rnorm(5), 6:10, rnorm(5)) colnames(my.mat) <- c("Turn", "Draw","Turn", "Draw") print(xtable(my.mat))

yields

\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
  \hline
 & Turn & Draw & Turn & Draw \\ 
  \hline
1 & 1.00 & -0.72 & 6.00 & 0.91 \\ 
  2 & 2.00 & 0.57 & 7.00 & 0.56 \\ 
  3 & 3.00 & 1.08 & 8.00 & 0.55 \\ 
  4 & 4.00 & 0.95 & 9.00 & 0.46 \\ 
  5 & 5.00 & 1.94 & 10.00 & 1.06 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

I want to filter out the \begin{table} and \end{table} lines. I can do this using gsub, but how to I get the results of print(xtable(... into a variable?

Thanks fo开发者_Go百科r the help Stack Overflow R community!


EDIT - Making progress

In my .Rnw, I have

\begin{tablehere}
{

<<echo=false,results=tex>>=
library(xtable)
my.mat <- cbind(1:5, rnorm(5), 6:10, rnorm(5))
colnames(my.mat) <- c("Turn", "Draw","Turn", "Draw")
#print(xtable(my.mat))

x <- capture.output(print(xtable(my.mat)))
x <- gsub("\\\\begin\\{tabular\\}.*", "", x, perl=TRUE)
x <- gsub("\\\\end\\{tabular\\}.*", "", x, perl=TRUE)
print(x)

@ 

 }
\end{tablehere}

which leads to

\begin{tablehere}
{

 [1] "% latex table generated in R 2.9.2 by xtable 1.5-5 package"
 [2] "% Mon May 17 20:23:09 2010"                                
 [3] "\\begin{table}[ht]"                                        
 [4] "\\begin{center}"                                           
 [5] ""                                                          
 [6] "  \\hline"                                                 
 [7] " & Turn & Draw & Turn & Draw \\\\ "                        
 [8] "  \\hline"                                                 
 [9] "1 & 1.00 & -1.76 & 6.00 & 0.70 \\\\ "                      
[10] "  2 & 2.00 & 1.58 & 7.00 & 2.57 \\\\ "                     
[11] "  3 & 3.00 & -1.80 & 8.00 & 0.47 \\\\ "                    
[12] "  4 & 4.00 & -2.25 & 9.00 & -0.63 \\\\ "                   
[13] "  5 & 5.00 & 1.99 & 10.00 & -0.35 \\\\ "                   
[14] "   \\hline"                                                
[15] ""                                                          
[16] "\\end{center}"                                             
[17] "\\end{table}"                                                  
 }
\end{tablehere}

which is so close. How do I get R to print the right way?


What about cat(x,sep='\n') instead of print(x)


This works for me:

x <- print(xtable(my.mat))
x <- gsub("\\\\begin\\{tabular\\}\\{rrrrr\\}", "", x)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜