Convert R matrix like `m<-rbind(c("x/(z+1)","x^2/(z+1)"),c("y/(z+1)","y^2/(z+1)"))` to table it to .doc

时间:2015-07-31 19:20:25

标签: latex r-markdown symbolic-math doc

I want to insert R matrix like m<-rbind(c("x/(z+1)","x^2/(z+1)"),c("y/(z+1)","y^2/(z+1)")) as a table in R Markdown than knit it to .doc.
I would like it in a neat form, such that all cells are separated by lines and all formulas displayed properly. I want to do it automatically from matrix I have.
I am thinking about thous formulas inside the matrix as simple examples of any formula that contains variables and arithmetic operations.
First I tried with more simple expression m<-rbind(c("x","x^2"),c("y","y^2")) with no result.

TeXForm(m)

library(Ryacas)
Sym(m)
TeXForm(m)

I got:

"$x$";

pander(m)

I got:

-------
 A   B 
--- ---
 x  x^2 

 y  y^2
-------

formulas in cells were displayed not properly.

knitr::kable(m)

I got:

|A  |B   |
|:--|:---|
|x  |x^2 |
|y  |y^2 |

It wasn`t displayed properly in .doc.

xtable(m)

I got LaTeX code which I was unable to knit in .doc. But when knitted in pdf formulas in cells were displayed not properly. I also tried print(xtable(m),type="html")
I wasn`t able to knit it to .doc, but in html document it gives results similar to previous.

Replace each element of matrix with LaTeX code

Apymtx<-function(m,f){m1<-m 
for (k in 1:nrow(m)){ for (l in 1:ncol(m)){m1[k,l]<-f(m[k,l])}}
return(m1)}
m<-Apymtx(m, TeXForm)

I got:

[,1]               [,2]                
[1,] "( TeXForm( x ) )" "( TeXForm( x^2 ) )"
[2,] "( TeXForm( y ) )" "( TeXForm( y^2 ) )"

Than I tried to change 'class' of TeXForm(m[1,1]) to 'character' with no result.

How to get table filed with formulas in R Markdown, and knit it to .doc?

2 个答案:

答案 0 :(得分:1)

您错过了pandoc解释Tex formulas between the dollar signs。 E.g:

> pander(data.frame(
+   A = c("$x^2$", "$\\frac{x}{y}$"),
+   B = c("$\\sum_{1}^{n}foobar_i$",
+         "$\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta$")))

--------------------------------------
      A                  B            
------------- ------------------------
    $x^2$      $\sum_{1}^{n}foobar_i$ 

$\frac{x}{y}$ $\cos (2\theta) = \cos^2
              \theta - \sin^2 \theta$ 
--------------------------------------

docx

中呈现罚款

enter image description here

修改:根据问题更新,让我更清楚您想要将数学公式转换为Ryacas的TeX,请参阅此方法。不幸的是,我无法在retclass="unquote"中使用yacas参数,这就是丑陋的字符串操作的原因:

> pander(apply(m, c(1, 2), function(x) gsub('\\"|;| ', '', yacas(TeXForm(x))$YacasForm)))

--------------- -------------------
$\frac{x}{z+1}$ $\frac{x^{2}}{z+1}$

$\frac{y}{z+1}$ $\frac{y^{2}}{z+1}$
--------------- -------------------
调用pander

MS Word输出:

enter image description here

答案 1 :(得分:0)

以下是基于答案标记为正确的解决方案的另一种变体。

library(Ryacas)
library(pander)
m<-rbind(c("x","x^2"),c("y","y^2"))
Apycs<-function(m){
library(Ryacas)
m1<-m 
for (k in 1:nrow(m)){ for (l in 1:ncol(m)){
m.2<-yacas(TeXForm(m[k,l]))[[2]]
m1[k,l]<-substr(m.2,2,nchar(m.2)-2)}}
return(m1)}
m<-Apycs(m)
pander(m)