2013-12-23 34 views
5

比方說,有R矩陣x在數學或公式環境R矩陣轉換成乳膠基質

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2"))) 

我寫一個報告特色LaTeX的方程,用降價-pandoc乳膠工作流程。 x是需要出現在這些方程中的矩陣之一。是否有可能以編程方式使基體的乳膠respresentation如下?:

\begin{bmatrix} 
2 & 12\\ 
3 & 17\\ 
5 & 10\\ 
7 & 18\\ 
9 & 13 
\end{bmatrix} 

理想情況下,報告中的代碼將東西的線路:

\begin{displaymath} 
\mathbf{X} = `r whatever-R-code-to-render-X` 
\end{displaymath} 

但是這可能是麻煩的,所以我一定會爲簡單的轉型而解決。

+0

附:在問過這個問題之後,我意識到編寫一個自定義函數來完成這項工作可能不會太困難,但也許這個功能已經存在了? –

+0

'Hmisc ::: latex'你在找什麼? – rawr

回答

10

您可以使用xtable包print.xtable方法和簡單的包裝腳本來設置一些默認參數。

bmatrix = function(x, digits=NULL, ...) { 
    library(xtable) 
    default_args = list(include.colnames=FALSE, only.contents=TRUE, 
         include.rownames=FALSE, hline.after=NULL, comment=FALSE, 
         print.results=FALSE) 
    passed_args = list(...) 
    calling_args = c(list(x=xtable(x, digits=digits)), 
        c(passed_args, 
        default_args[setdiff(names(default_args), names(passed_args))])) 
    cat("\\begin{bmatrix}\n", 
     do.call(print.xtable, calling_args), 
     "\\end{bmatrix}\n") 
} 

好像你在找什麼

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2"))) 

bmatrix(x) 
## \begin{bmatrix} 
## 2.00 & 12.00 \\ 
## 3.00 & 17.00 \\ 
## 5.00 & 10.00 \\ 
## 7.00 & 18.00 \\ 
## 9.00 & 13.00 \\ 
## \end{bmatrix} 

,並使用沒有小數位喜歡你的例子。

bmatrix(x, digits=0) 
## \begin{bmatrix} 
## 2 & 12 \\ 
## 3 & 17 \\ 
## 5 & 10 \\ 
## 7 & 18 \\ 
## 9 & 13 \\ 
## \end{bmatrix} 
+0

就是這樣。謝謝。 –

5

對於未來的參考,下面是我後來自己寫的函數:

matrix2latex <- function(matr) { 

printmrow <- function(x) { 

    cat(cat(x,sep=" & "),"\\\\ \n") 
} 

cat("\\begin{bmatrix}","\n") 
body <- apply(matr,1,printmrow) 
cat("\\end{bmatrix}") 
} 

它不需要外部包裝。由於某種原因,apply在輸出結束時產生了NULL(實際返回?)。這是通過將返回分配給body變量來解決的,否則該變量是無用的。接下來的任務是在knitr內部render the output of that function in LaTeX

0

,如果有人通過\bordermatrix需要圓矩陣與邊界,我追加@ Maxim.K的功能來實現這一目標。

m2l <- function(matr) { 
    matr <- round(x = matr, digits = 2) # sadly this is necessary because given this function, the options(digits = 2) does not work 
    matr2 <- data.frame(c("~",rownames(matr))) # add rownames 
    for (r in colnames(matr)) { # add col contents and colnames 
     matr2 <- cbind(matr2, c(r, matr[,r])) 
    } 
    printmrow <- function(x) { 
     ret <- paste(paste(x, collapse = " & "), "\\cr") 
     sprintf(ret) 
    } 
    out <- apply(matr2, 1, printmrow) 
    out2 <- paste("\\bordermatrix{", paste(out, collapse = ' '),"}") 
    return(out2) 
} 

很可怕的代碼,我知道,但完成了工作。

也許這對其他人會有幫助。

能好看,尤其是對相關矩陣和這樣的東西:

tex

+0

不幸的是,出於某種原因,輸出只在將'* .Rmd'渲染爲PDF(通過LaTeX)而不是HMTL(通過Markdown)時才起作用。 不知道爲什麼,在這裏提出它:http://stackoverflow.com/questions/30740613/how-do-i-get-latex-math-typeset-matrix-with-borders-in-html-output-from-rmd – maxheld