2014-09-22 16 views
1

我正在嘗試使用外部代碼塊與knitr並想參數化塊。也許我完全誤解了代碼塊選項的概念,但這是我試圖做的。在我的RNW文件我有:具有參數的knitr外部代碼塊

\documentclass[12pt,a4paper]{article} 
\usepackage[latin1]{inputenc} 
\usepackage{amsmath} 
\usepackage{amsfonts} 
\usepackage{amssymb} 
\usepackage{graphicx} 

\begin{document} 

<<locate_external_code, include=FALSE, echo=FALSE, message=FALSE, warning=FALSE>>= 
library(knitr) 
read_chunk('mwex.r') 
@ 

<<setUpMatrices, echo=TRUE, include=FALSE, message=FALSE, warning=FALSE>>= 
@ 

Want to select M1, M2, etc. by `calling' getMatrix setting parameter select to the required value e.g. M1 

<<getMatrix, echo=FALSE, include=TRUE, results='asis', message=FALSE, warning=FALSE, select='M1'>>= 
@ 

e.g. M2 
<<getMatrix, echo=FALSE, include=TRUE, results='asis', message=FALSE, warning=FALSE, select='M2'>>= 
@ 

The calls don't work but I can get the matrices like this: \newline 
<<getM1, echo=FALSE, include=TRUE, results='asis', message=FALSE, warning=FALSE>>= 
@ 

\end{document} 

在我的R檔,我有:

## ----setUpMatrices 
library(xtable) 
NP<-matrix(c(0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1/3, 1/3, 1/3, 0, 0, 1/3, 1/3, 1/3, 0, 0),5,5,byrow=TRUE) 
UP<-matrix(c(1/3, 1/3, 1/3, 0, 0),1,5,byrow=TRUE) 
mat<-xtable(NP,align=rep('',ncol(NP)+1)) 
M1<-paste('$',print(mat, floating=FALSE, comment=FALSE,tabular.environment="pmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE),'$',sep='') 

mat<-xtable(UP,align=rep('',ncol(NP)+1)) 
M2<-paste('$',print(mat, floating=FALSE, comment=FALSE,tabular.environment="pmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE),'$',sep='') 


## ----getMatrix 
cat(select) 

## ----getM1 
cat(M1) 

getM1工程確定,但參數化getMatrix調用導致在r中報告"Error: object 'select' not found"

+1

我看不到你定義了一個叫做select的對象。此外,您可以設置一些全局塊選項,以便您不必爲每個塊輸入這些選項 – rawr 2014-09-22 14:39:28

+0

我天真地認爲代碼塊選項將設置變量select ='M1' – stegzzz 2014-09-22 15:14:00

+0

我從未使用過該選項。你能指點我的描述 – rawr 2014-09-22 15:33:07

回答

0

看來你有一個誤解:代碼塊選項不是R工作區中的對象。你有一個塊選項select='M1',這並不意味着它會給你一個變量select在你的工作區。塊選項用於調整代碼組塊的行爲。

您沒有M1問題,因爲您在代碼塊setUpMatrices中定義了它。

0

謝謝你@Yihui。

因此,爲了實現我的目標,我RNW代碼,我已經寫了:

<<echo=FALSE>>= 
select<-'M2' 
@ 
<<getMatrix, echo=FALSE, include=TRUE, results='asis', message=FALSE, warning=FALSE>>= 
@ 

,並在R檔我有

## ----getMatrix 
cat(get(select)) 

這似乎有點笨重有兩個塊進行通信這種r代碼,但它工作正常。我現在明白,塊選項不是實現它的方式,但也許有一個更優雅的解決方案?