針織。將一個函數分成幾個區塊

針織。將一個函數分成幾個區塊

是否可以使用 knit 將 R 函數拆分為多個區塊(出於文檔原因)?這是一個 MWE:

\documentclass{article}
\begin{document}
Part1 gives salutation. 
<<part1>>=
hello <- function(x){
  print("Hi")
@
Part2 adds the name.
<<part2>>=
  print(x)}
@
\end{document}

答案1

有一個chunk名為 的選項eval,它控制 R 是否實際計算代碼FALSE

另外,如一輝在評論中指出,您可以使用和<<part3, ref.label=c('part1', 'part2')>>=來組合併實際評估代碼。part1part2

在下面的 MWE 中,我添加了這樣一個part3, 設置echoFALSE這樣就不會出現任何內容,因為您已經在第 1 部分和第 2 部分中顯示了代碼part4。位置新增您定義的函數的參數。

\documentclass{article}

\begin{document}

Part1 gives salutation. 
<<part1, eval=FALSE>>=
hello <- function(x){
  print("Hi")
@
Part2 adds the name.
<<part2, eval=FALSE>>=
  print(x)}
@

<<part3, ref.label=c('part1', 'part2'), echo=FALSE>>=
@

<<part4>>=
hello("Dan Wright")
@

\end{document}

在此輸入影像描述

答案2

閱讀可用的區塊選項看看如何使用它們

在這種特殊情況下,echo eval選項可以一起使用...

<<the_func, echo=FALSE>>=
hello <- function(x){
  print("Thanks")
  print(x)
}
@

<<the_func, echo=1:2, eval=FALSE>>=
@

<<the_func, echo=3:4, eval=FALSE>>=
@

答案3

ref.label 選項解決了這個問題。這是工作範例。

\documentclass{article}
\begin{document}
Part1 gives salutation. 
<<part1,eval=FALSE>>=
hello <- function(x){
  print("Thanks")
@
Part2 adds the name.
<<part2,eval=FALSE>>=
  print(x)}
@
<<part3,echo=FALSE,ref.label=c('part1','part2')>>=
@
<<executefunction>>=
hello('Adam and Yihue')
@
\end{document}

相關內容