//  間瀬茂

COLOR(blue){SIZE(20){Sweave ユーザーマニュアル}} by Friedrich Leisch, R Version 2.0.0~

//COLOR(red){SIZE(16){(翻訳作業中、 2005.05.05  開始)}}~
// 翻訳暫定終了 2007.02.21 長山泰秀(4.1以降)

#contents

* 1. はじめに [#z886b078]

 Sweave はドキュメントの自動作成のために、テキストと R コードを混在させるための柔軟な枠組を提供する。単一のソースファイルがドキュメントと R コードの双方を含むファイルから
 ドキュメントテキストと
 R コード、とともに(もしくは)
 コードの出力(テキスト、グラフ)
を織り込んだ最終ドキュメントを生成する。これは、入力データが変更された場合レポートを再生成し、レポートを含む同じファイルに、解析手順を再生するコードをドキュメント化する。解析の完全な R コードが noweb 構文(Ramsey, 1998)を用い、LaTeX ドキュメントに埋め込まれる。従って、LaTeX (高品位タイプセッティング)と R (データ解析) のすべての能力を同時に使用することができる。ダイナミックなレポート生成に関する一般的な考察や、他システムについては、Leisch (2002) とそこにあげられた参考文献を参照せよ。~
 Sweave は実際の翻訳に異なるドライバーを使うというモジュラー型コンセプトを使う。明らかに,別々のドラ−バーは別々のマークアップ言語(LaTeX、HTML、…)が必要とされる。CRAN のいくつかのパッケージは他の文書処理システムを提供する(付録Aを参照せよ)。

* 2. Noweb ファイル [#w70e936f]

* 2. Noweb ファイル [#v20963a6]

 Noweb (Ramsey, 1998) は,プログラムソースコードと対応する文書を一つのファイルにするまとめるための,単純な,可読性の高いプログラミングツールである。noweb ファイルは「チャンク」と呼ばれる,コードと文書のセグメントからなる。

ドキュメントチャンクは最初の文字としてサイン (@) を持ち、その後には空白か改行文字が続く。典型的には、ドキュメントチャンクはLATEX のようなマークアップ言語によるテキストを含むであろう。コードチャンクは、最初の行が <<name >>= で始まり、その行の残りはコメントであり無視される。

最初のチャンクは既定ではドキュメントである。noweb の最も単純な用法では、(オプションの)コードチャンクの名前は、ソースコードファイルの名前を与え、ツール notangle を用いて、noweb ファイルからコードチャンクを抜き出すことができる。複数のコードチャンクが同じ名前を持っても良い。対応するコードチャンクはソースコードが抜き出されるとき、連結される。noweb はコードチャンクの相互参照用の追加機構 (二重鈎括弧演算子等)を持つが、Sweave は現在この機能をサポートしていないので、ここでは解説しない。

脚注:~
1 See Becker et al. (1988) and Chambers (1998) for definitions of the S language, and Venables and Ripley (2000)
for details on the term S engine and detailed descriptions of differences between various implementations of the S
language.~
2 R システム:http://www.R-project.org~
3 LATEX システム:http://www.ctan.org~
4 S-PLUS システム:http://www.insightful.com~

* 3. Sweave ファイル [#pa7f64b0]

** 3.1 簡単な例 [#d0cd9592]

Sweave のソースファイルは正規の noweb ファイルであり、最終的な出力への幾つかの追加の制御を許すための幾つかの追加構文を持つ。伝統的な noweb ファイルは拡張子 .nw を持つが、これはまた Sweave  ファイルにも有効である( そして完全にサポートされている)。更に、 Sweave は現在、拡張子 .rnw, .Rnw, .snw そして .Snw を持つファイルを Sweave 拡張を持つ noweb ファイルとして認識する。この文章では .Snw で統一する。

Sweave ファイルの一つの最小例を図 1 に示す。これは単純な LATEX ドキュメントに埋め込まれた二つのコードチャンクを持つ。Sweave はこれを図 2,3 に示した LATEX ドキュメントに変換する。example-1.Snw と example-1.tex の最初の違いは LATEX のスタイルファイル Sweave.sty が自動的にロードされる事である。これは S 入力と出力の組版のための環境(LATEX 環境 Sinput と Soutput)を提供する。その他の点では、example-1.Snw から example-1.tex へドキュメントチャンクは一切の変更無しにコピーされる。

 図 1: 最小の Sweave ファイル: example-1.Snw
 (訳注:<<...>> は空白無しで行の先頭に置かないとまずいらしい)
 
 \documentclass[a4paper]{article}
 \title{Sweave Example 1}
 \author{Friedrich Leisch}
 \begin{document}
 \maketitle
 この例では \texttt{kruskal.test} のヘルプページからの実行例の一部を \LaTeX{} ドキュメントに
 埋め込む:
 <<>>=
 data(airquality)
 library(stats)
 kruskal.test(Ozone ~ Month , data = airquality)
 @
 これはオゾンの分布の位置パラメータが月毎に有意に変化することを示している。最後にデータの箱型図を
 取り込む:
 \begin{center}
 <<fig =TRUE, echo =FALSE>>=
 boxplot(Ozone ~ Month , data = airquality)
 @
 \end{center}
 \end{document}

Sweave の既定動作が使われ、S 命令とその対応する出力が LATEX ファイルに変換され、それぞれ Sinput, Soutput 環境に埋め込まれている。二番目のコードチャンクは noweb 構文への Sweave 拡張の一つを示している。コードチャンク名を用いて最終出力を制御するオプションを Sweave に引き渡すことが出来る。チャンクは図チャンク (fig=TRUE) とマークされ、それにより、Sweave はチャンク中の命令により作られるプロットに対応する EPS と PDF ファイルを生成する。更に、\includegraphics{example-1-002} 命令が LATEX ファイルに埋め込まれる(図のファイル名の選択に関する詳細はこのマニュアルの後の方で述べられる)。オプション echo=FALSE は S 入力を最終ドキュメントに含めない(Sinput 環境無し)事を指示する。

 図 2: 命令 Sweave("example-1.Snw") の出力が以下のファイル example-1.tex である。
 
 \documentclass[a4paper]{article}
 \title{Sweave Example 1}
 \author{Friedrich Leisch}
 \usepackage{Sweave}
 \begin{document}
 \maketitle
 この例では \texttt{kruskal.test} のヘルプページからの実行例の一部を \LaTeX{} ドキュメントに
 埋め込む:
 \begin{Schunk}
 \begin{Sinput}
 > data(airquality)
 > library(stats)
 > kruskal.test(Ozone ~ Month , data = airquality)
 \end{Sinput}
 \begin{Soutput}
 Kruskal - Wallis rank sum test
 data : Ozone by Month
 Kruskal - Wallis chi - squared = 29.2666 , df = 4, p- value = 6.901e -06
 \end{Soutput}
 \end{Schunk}
 これはオゾンの分布の位置パラメータが月毎に有意に変化することを示している。最後にデータの箱型図を
 取り込む:
 \begin{center}
 \includegraphics{example-1-002}
 \end{center}
 \end{document}

#ref(example-1.png)

** 3.2 Sweave のオプション [#t2d1063c]

オプションは、コードチャンクとそれらの出力(テキスト、図)を .Snw ファイルから .tex ファイルにどのように変換するかを制御する。全てのオプションは key=value という形式を持ち、ここで value は数値、文字列、または論理値で良い。複数のオプションを(コンマで区切って)同時に指定することが出来、全てのオプションは値(コンマや等号記号を含んではならない)を持たなければならない。論理値オプションは値、true, false, t, f もしくはその大文字版をとることが出来る。.Snw ファイルでは、オプションは

 1. 一つのコードチャンクの先頭におかれた矢印括弧の中(このチャンクに対してだけ有効)
 2. ドキュメントチャンクの任意の場所におかれた命令 
    \SweaveOpts{opt1=value1, opt2=value2, ..., optN=valueN}
    (これは、以降のドキュメント全て、つまり、宣言以降の全てのコードチャンク、に対して有効)。

のいずれかによって、指定できる。したがって、ドキュメントの先頭部に置かれた \SweaveOpts 文は、全てのコードチャンクに対する既定値を設定する。


どのオプションがサポートされているかは使用されるドライバに依存する。全てのドライバは少なくとも以下のオプション(それらは、もしあれば既定動作を持つ)をサポートすべきである:

 engine=S:    それぞれのコードチャンクを、どの S エンジンが処理できるかを記述する文字列。可能な値は、
              例えば、S, R, S3 もしくは S4 である。各ドライバは対応可能なコードチャンクだけを処理
              し、それ以外は無視する。
 split=FALSE: 論理値。もし TRUE なら、出力は複数のファイルに配分される。もし FALSE なら、
              全ての出力は一つのファイルに書き込まれる。詳細はドライバに依存する。
 label:       コードチャンクに対するラベルで、split=TRUE の時、ファイル名の作成に使われる。もし
              ラベルが、label.engine という形式ならば、その拡張子は以後使われる前に取り除かれる
              (例えば、ラベル hello.S は hello に短縮される)。

コードチャンク名中の最初(そして最初だけ)のオプションは名前が無くても良く、その際は、それがラベルとされる。つまり、コードチャンクが

 <<hello.S, split=FALSE>>

で始まれば、それは

 <<split=FALSE, label=hello.S>>

と同じであるが、しかし

 <<split=FALSE, hello.S>>

では構文エラーになる。ラベルに対する名前無しの第一引数は noweb との互換性のために必要となる。もし \SweaveOpts だけがオプションの設定に使われれば、Sweave ファイルは noweb と完全に互換(コードチャンク名中に、ファイル名だけが登場するので)となるように書くことが出来る。

** 3.3 テキスト中で数値を使う [#xc8f9c16]

テキストチャンク中で S オブジェクトの値を使うための限られた機能がある。\Sexpr{expr} という表現は、表現式 expr を文字ベクトルに変換することにより得られる文字列で置き換えられるが、この ベクトルの最初の要素だけが使われる。例えば \Sexpr{sqrt(9)} は(引用符無しの)文字列 ’3’に置き換えられる。表現式はコードチャンクと同一の環境で評価されるので、式が登場する前に登場したコードチャンク中で定義された、全てのオブジェクトにアクセス可能である。表現式は任意の適正な S コードを含んで良く、波括弧だけが許されない。これは実際には制限にはなら無い。なぜなら、より複雑な計算は隠されたコードチャンク中で容易に済ませておくことが出来、それからその結果を \Sexpr 中に使えば良いからである。

** 3.4 コードチャンクの再利用 [#c369f6ff]

名前付きのコードチャンクは、ドキュメント中で後に現れた他のコードチャンク
中で再利用出来る。次の簡単な例

 <<a>>=
 x <- 10
 @
 <<b>>=
 x + y
 @
 <<c>>=
 <<a>>
 y <- 20
 <<b>>
 @

を考えよう。これは、最後のコードチャンクを次のように定義するのと同値である:

 <<c>>=
 x <- 10
 y <- 20
 x + y
 @

チャンク参照演算子 <<>> は他の追加の Sweave オプション無しの、チャンク名だけを引数に取る。

** 3.5 構文の定義 [#c12d23c7]

これまでは(既定の) noweb 構文だけを使った Sweave ファイルの事だけを話してきた。しかしながら、Sweave は、テキスト中の数値の利用や、コードチャンクの再利用により、ユーザがドキュメントやコードチャンクをマーキングする構文を再定義することを許す。図 4 は SweaveSyntaxLatex 定義を用いた図 1 の例を示す。コードチャンクは、ここではS コード環境中に含められ、S コード ref{chunkname} を用いて、コードチャンクが再利用される。他の全ての演算子は noweb スタイルの構文と同じである。ドキュメントにどの構文を使うかは、入力ファイルの拡張子で決まる。拡張子 .Rtex や .Stex を持つファイルはLATEX 風の構文を持つと仮定される。または、構文は任意の箇所で、ドキュメントチャンク中の最初の行に置かれた命令

 \SweaveSyntax{SweaveSyntaxLatex}

もしくは

 \SweaveSyntax{SweaveSyntaxNoweb}

で変更できる。構文定義は幾つかの Sweave 命令に対する正規表現の単純なリストである。例の最初にあげられた二つの定義を見よ。(より詳細な使い方は API が安定した後で提供されるであろう。)

*4 Tangling (縺れ)と weaving (編みあげ) [#gf9a6b78]

Sweave システムに対するユーザフロントエンドは二つの S 関数 Stangle() と Sweave() であり、ともに R の基本パッケージ utils に含まれる (http://www.R-project.org)。Stangle は .Snw ファイルからコードチャンクだけを取り出すし、一つもしくは複数のファイルに書き出すのに使える。

 Figure 4: LATEX 構文を用いた Sweave ファイル例: example-1.Stex.
 \documentclass[a4paper]{article}
 \title{Sweave Example 1}
 \author{Friedrich Leisch }
 \begin{document }
 \maketitle
 この例では \texttt{kruskal.test} のヘルプページ中の例の
 一部を \LaTeX{} 文章に埋め込む:
 \begin{Scode}
   data(airquality)
   library(ctest)
   kruskal.test(Ozone ~ Month , data = airquality)
 \end{Scode}
 これはオゾンの分布の位置パラメータが月毎に有意に変動する
 ことを示す。次に、データのボックスプロットを含める:
 \begin{center}
   \begin{Scode}{fig=TRUE , echo = FALSE}
     boxplot(Ozone ~ Month , data = airquality)
   \end{Scode}
 \end{center}
 \end{document}

Sweave は S エンジンを用いてコードチャンクを実行し、それらを対応する入力 and/or 出力に置き換える。Stangle は実際は Sweave に対する単なるラッパ関数であり、既定で tangling ドライバを weaving ドライバの代わりに使う。

 Sweave レポートの自動作成
 
 説明
 Sweave はレポートの自動作成のためにテキストと S コードを混在させるための
 柔軟な枠組を提供する。基本的なアイデアは、S コードをその出力で置き換え、
 最終的な文章がテキストと統計解析結果だけを含むようにすることである。
 
 用法
 Sweave(file, driver = RweaveLatex(), syntax = getOption("SweaveSyntax"), ...)
 Stangle(file, driver = Rtangle(), syntax = getOption("SweaveSyntax"), ...)
 
 引数
 file     Sweave ソースファイル名
 driver   実際に使われるドライバ、以下の詳細を見よ
 syntax   クラス SweaveSyntax のオブジェクトか、その名前を持つ文字列
          既定のインストールでは SweaveSyntaxNoweb と SweaveSyntaxLatex が提供される
 ...      ドライバの設定関数に引き渡される追加引数
 
 詳細
 (latex のような)文章作成マークアップと S コードを一体化することにより、レポートを自動
 作成する。最終的なマークアップファイルでは S コードはその出力で置き換えられる。これは、
 もし入力データが変わってもレポートを再生成し、レポートを生成したのと同じファイルに、行っ
 た解析を再現するコードをドキュメント化する。Sweave は文章とコードチャンク(もしくはその
 出力を)を一つのファイルにまとめる。Stangle は Sweave ファイルから真正の S ソースファイル
 をつくり出すコードだけを取り出す(そして、それを source  関数で実行できる)。
 \Sexpr{} 文中のコードは S tangle により無視される。Stangle は既定では簡単なドライバを使う
 Sweave へのフロントエンドであり、文章部分を取り去り、使用中の S エンジンが理解する全ての
 コードチャンクを連結する。
 
 フック関数
 各コードチャンクが評価される前に、幾つかのフック関数を実行できる。もし getOption("SweaveHooks") 
 が設定されていれば、それはフック関数の集まりとされる。一つのコードチャンク (echo, print, . . . )
 の各論理オプション毎に一つのフック関数を指定することができ、それは対応するオプションが TRUE 
 の時、そしてその時だけ実行される。フックは  getOption("SweaveHooks") が返すリストの名前付き
 成分でなければならず、引数を持たない関数でなければならない。つまり、もしオプション "SweaveHooks" 
 が list(fig = foo) と定義されており、foo が関数なら、それは各図チャンク中のコードの前に実行
 されるであろう。これは一連の図チャンク中の作図パラメータに対する既定値を設定するのに便利である。
 ユーザは新しい Sweave オプションと、それらに関連する任意のフック関数を自由に定義できることを
 注意しよう。例えば、大局的環境中の全てのオブジェクトを取り除くオプション clean に対するフック
 関数を定義できる。すると clean=TRUE である全てのコードチャンクは空の作業スペースで始められる
 ことになるであろう。
 
 
 構文上の定義
 Sweave は,ドキュメントとテキストチャンクを記述するのに非常に柔軟な構文の枠組を許す.
 デフォルトはnowebスタイルの構文であるが,代わりにlatexスタイルの構文を使うこともできる.
 詳しくはユーザーマニュアルを参照.
 
 Author(s)
 Friedrich Leisch
 References
 Friedrich Leisch: Sweave User Manual, 2002
 http://www.ci.tuwien.ac.at/~leisch/Sweave
 Friedrich Leisch: Dynamic generation of statistical reports using literate data analysis. In W.
 Hrdle and B. Rnz, editors, Compstat 2002 - Proceedings in Computational Statistics, pages
 575-580. Physika Verlag, Heidelberg, Germany, 2002. ISBN 3-7908-1517-9.
 
 See Also
 RweaveLatex, Rtangle
 
 Examples
 testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils")
 ## create a LaTeX file
 Sweave(testfile)
 ## create an S source file from the code chunks
 Stangle(testfile)
 ## which can be simply sourced
 source("Sweave-test-1.R")

// ** 4.1 The RweaveLatex driver
** 4.1 RweaveLatex ドライバー [#i9d73ca4]
//This driver transforms .Snw files with LATEX documentation chunks and R code chunks to proper
// LATEX files (for typesetting both with standard latex or pdflatex).
このドライバーは,
LaTeX ドキュメントのチャンクと
R コードチャンクをもった
.Snw ファイルを
適切なLaTeXファイル
(通常のlatex と pdflatex でタイプセットするための)へと変換する.



  RweaveLatex R/LaTeX Driver for Sweave
  
  説明
  LaTeX ファイルの中で Rコードチャンクを変換する Sweave のためのドライバー
  
  使用法
    RweaveLatex()
    RweaveLatexSetup(file, syntax, output = NULL, quiet = FALSE,
      debug = FALSE, echo = TRUE, eval = TRUE,
      split = FALSE, stylepath = TRUE,
      pdf = TRUE, eps = TRUE)
  
  引数
    file Name of Sweave source file.
    syntax An object of class SweaveSyntax.
    output Name of output file, default is to remove extension ‘.nw’, ‘.Rnw’ or 
      ‘.Snw’
      and to add extension ‘.tex’. Any directory names in file are also removed
      such that the output is created in the current working directory.
    quiet If TRUE all progress messages are suppressed.
    debug If TRUE, input and output of all code chunks is copied to the console.
    stylepath If TRUE, a hard path to the file ‘Sweave.sty’ installed with this package is
      set, if FALSE, only \usepackage{Sweave} is written. The hard path makes
      the TeX file less portable, but avoids the problem of installing the current
      version of ‘Sweave.sty’ to some place in your TeX input path. The argument
      is ignored if a \usepackage{Sweave} is already present in the Sweave source
      file.
    echo set default for option echo, see details below.
    eval set default for option eval, see details below.
    split set default for option split, see details below.
    pdf set default for option pdf, see details below.
    eps set default for option eps, see details below.
  
  サポートされているオプション
    RweaveLatex supports the following options for code chunks (the values in parentheses show
    the default values):
  
    echo: logical (TRUE). Include S code in the output file?
    eval: logical (TRUE). If FALSE, the code chunk is not evaluated, and hence no text or graphical
      output produced.
    results: character string (verbatim). If verbatim, the output of S commands is included in
      the verbatim-like Soutput environment. If tex, the output is taken to be already proper
      latex markup and included as is. If hide then all output is completely suppressed (but
      the code executed during the weave).
    print: logical (FALSE) If TRUE, each expression in the code chunk is wrapped into a print()
      statement before evaluation, such that the values of all expressions become visible.
    term: logical (TRUE). If TRUE, visibility of values emulates an interactive R session: values of
      assignments are not printed, values of single objects are printed. If FALSE, output comes
      only from explicit print or cat statements.
    split: logical (FALSE). If TRUE, text output is written to separate files for each code chunk.
    strip.white: logical (TRUE). If TRUE, blank lines at the beginning and end of output are
      removed.
  
    prefix: logical (TRUE). If TRUE generated filenames of figures and output have a common
      prefix.
    prefix.string: a character string, default is the name of the ‘.Snw’ source file.
    include: logical (TRUE), indicating whether input statements for text output and includegraphics
      statements for figures should be auto-generated. Use include = FALSE if the
      output should appear in a different place than the code chunk (by placing the input line
      manually).
    fig: logical (FALSE), indicating whether the code chunk produces graphical output. Note that
      only one figure per code chunk can be processed this way.
    eps: logical (TRUE), indicating whether EPS figures shall be generated. Ignored if fig =
      FALSE.
    pdf: logical (TRUE), indicating whether PDF figures shall be generated. Ignored if fig =
      FALSE.
    width: numeric (6), width of figures in inch.
    height: numeric (6), height of figures in inch.
  
  Author(s)
    Friedrich Leisch
  
  References
    Friedrich Leisch: Sweave User Manual, 2002
    http://www.ci.tuwien.ac.at/~leisch/Sweave
  
  See Also
    Sweave, Rtangle

*** 4.1.1 分離されたファイルへの書き込み [#x8d89f6a]

// *** 4.1.1 Writing to separate files
// If split is set to TRUE, then all text corresponding to code chunks (the Sinput and Soutput
// environments) is written to seperate files. The filenames are of form prefix.string-label.tex,
// if several code chunks have the same label, their outputs are concatenated. If a code chunk has no
// label, then the number of the chunk is used instead. The same naming scheme applies to figures.

もしも,splitが真にセットされると,コードチャンクに対応するすべてのテキスト(Sinput,Soutput環境)は分離された別のファイルに書き込まれる.ファイル名は,prefix.string-label.tex の形式となる.もしも複数のコードチャンクが同じラベルをもっていると,その出力は連結される.もしもコードチャンクがラベルをもたなければ,かわりにチャンクの番号が使われる.同じ命名のスキームが図にも適用される.

// *** 4.1.2 LATEX style file and figure sizes [#i05aed9a]
*** 4.1.2 LaTeX のスタイルファイルと図のサイズ [#s5a0dc83]

// The driver automatically inserts a \usepackage{.../Sweave.sty} command
// as last line before the \begin{document} statement of the final LATEX
// file if no \usepackage{Sweave} is found in the Sweave source file. 
// This style file defines the environments Sinput and Soutput for
// typesetting code chunks. 
もしも Sweave ソースファイルに \usepackage{Sweave.sty} が見付からなければ,ドライバーは自動的に,最終的な LaTeX ファイルの \begin{document} 宣言の前の最後の行に \usepackage{.../Sweave.sty} を挿入する.このスタイルファイルは,コードチャンクのタイプセットのために Sinput,Soutput 環境を定義する.

// If you do not want to include the standard style file, e.g., because
// you have your own definitions for Sinput and Soutput environemts in a
// different place, simply insert a comment like % \usepackage{Sweave} in
// the preamble of your latex file, this will prevent automatic insertion
// of the line. Sweave.sty also sets the default LATEX figure width
// (which is independent of the size of the generated EPS and PDF
// files). 
もしも,たとえばあなたが自分で,別の場所にSinput,Soutput環境を定義しているといったようなことで標準的なスタイルファイルを使いたくないときには,LaTeXファイルのプリアンブルに% \usepackage{Sweave}といったようなコメント行を挿入するだけで,自動的に行を挿入することを抑止できる.~
Sweave.sty は,既定の LaTeX の図の幅をセットする(これは生成された EPS と PDF ファイルのサイズとは独立である).

// The current default is
現在の既定値は,

 \setkeys{Gin}{width=0.8\textwidth}

// if you want to use another width for the figures that are
// automatically generated and included by Sweave, simply add a line
// similar to the one above after \begin{document}. 
であり,図について,Sweaveが自動的に生成してインクルードするものとはちがう他の幅を使いたいときには,\begin{document}のあとに,上のものと同じ行を付け加えるだけでよい.

// Note that a new graphics device is opened for each figure chunk
// (option fig=TRUE), hence all graphical parameters of the par() command
// must be set in each single figure chunk and are forgotten after the
// respective chunk (because the device is closed when leaving the
// chunk). 
それぞれのフィギュアチャンク(option fig=TRUE)ごとに,新しいグラフィックデバイスがオープンされるので,par() コマンドのすべてのグラフィカルパラメータはひとつひとつのフィギュアチャンクでセットする必要があり,それぞれのチャンクのあとでは忘れ去られる(なぜならチャンクからはなれるときにはデバイスはクローズされるので).

// Attention: One thing that gets easily confused are the width/height
// parameters of the R graphics devices and the corresponding arguments
// to the LATEX \includegraphics command. 
注意:R グラフィックデバイスのパラメータ width/height はLaTeX の\includegraphics コマンドの対応する引数と混乱しやすい.

// The Sweave options width and height are passed to the R graphics
// devices, and hence affect the default size of the produced EPS and PDF
// files. 
Sweave の widthとheight オプションは,R のグラフィックデバイスに渡され,したがって作成される EPS と PDF ファイルの既定サイズに影響をあたえる.

// They do not affect the size of figures in the document, by default
// they will always be 80% of the current text width. 
そしてそれは,ドキュメントの中の図のサイズには影響せず,既定値では常に現在のテキスト幅の80%である.
// Use \setkeys{Gin} to modify figure sizes or use explicit
// \includegraphics commands in combination with Sweave option
// include=FALSE. 
図のサイズを変更するには,\setkeys{Gin} を使用するか,Sweave のオプション include=FALSEと組み合わせて明示的に\includegraphicsコマンドを使う.

// *** 4.1.3 Prompts and text width for that
*** 4.1.3 プロンプト記号とテキストの幅 [#h0f19a7b]

//As of R version 1.6.0 the driver gets the prompts used for input lines and continuation lines from
// R’s options() settings. To set new prompts use somthing like
// options(prompt="MyR> ", continue="...")
// see help(options) for details. Similarly the text width is controlled by option "width".
R バージョン1.6.0 と同じように,ドライバーは入力行と継続行に使われるプロンプトを,R の options() の設定から得ている.options(prompt="MyR> ", continue="...")といったような新しいプロンプトを設定するには,詳細はhelp(options)で見ること.同じく,テキストの幅も option "width" で制御されている.

// ** 4.2 The Rtangle driver
** 4.2 Rtangle ドライバー [#b7f415b2]

// This driver can be used to extract S and R code chunks from a .Snw file. Code // chunks can either
// be written to one large file or seperate files (one for each label). The options split, prefix,
// prefix.string and engine have the same defaults and interpretation as for the // RweaveLatex
// driver. Use the standard noweb command line tool notangle if other chunks than // R or S code
// should be extracted.
このドライバーは,.SnwファイルからSとRのコードを抽出するために使うことができる.コードチャンクはひとつの大きなファイルへ書き込むことも,分離されたファイルへ書き込むこともできる(それぞれのラベルについてひとつづつ).split, prefix, prefix.string, engine のオプションは,RweaveLatex? ドライバーと同じ既定値と動作をもつ.もしもRやSコードではないチャンクを抽出すべきときは,通常のnowebコマンドラインツールであるnotangleを使うこと.


 Rtangle R Driver for Stangle
 
 説明
   A driver for Stangle that extracts R code chunks.
 
 使用法
   Rtangle()
   RtangleSetup(file, syntax, output = NULL, annotate = TRUE,
     split = FALSE, prefix = TRUE, quiet = FALSE)
 
 引数
   file Name of Sweave source file.
   syntax An object of class SweaveSyntax.
   output Name of output file, default is to remove extension ‘.nw’, ‘.Rnw’ or ‘.Snw’
     and to add extension ‘.R’. Any directory names in file are also removed
     such that the output is created in the current working directory.
     annotate By default, code chunks are seperated by comment lines specifying the names
     and numbers of the code chunks. If FALSE, only the code chunks without
     any decorating comments are extracted.
   split Split output in single files per code chunk?
   prefix If split = TRUE, prefix the chunk labels by the basename of the input file
     to get output file names?
   quiet If TRUE all progress messages are suppressed.
 
 Author(s)
   Friedrich Leisch
 
 References
   Friedrich Leisch: Sweave User Manual, 2002
   http://www.ci.tuwien.ac.at/~leisch/Sweave
 
 See Also
   Sweave, RweaveLatex
 
 Acknowledgements
   The author wants to thank Vince Carey, Robert Gentleman, Kurt Hornik, Markus J¨antti, Brian
   Ripley, Anthony Rossini, and Dietrich Trenkler for providing valuable comments and ideas, testing
   development versions of the software or fixing bugs.

// * A Frequently Asked Questions 
* FAQ: しばしば聞かれる質問 [#i168c9e1]

// ** A.1 Where can I find the manual and other information on Sweave? 
** A.1 どこでSweaveのマニュアルやその他の情報を入手できますか? [#xb5b3c86]

// The newest version of the Sweave manual can always be found at the Sweave homepage
// http://www.ci.tuwien.ac.at/~leisch/Sweave
// where you also find several example files, and the lisp and shell code snippets of the FAQ. In
// addition, the homepage has several papers on Sweave like the CompStat paper and the 2-part
// miniseries from R News (Issues 2/3 and 2/3).
最新のSweaveのマニュアルはいつも[[Sweaveホームページ:http://www.stat.uni-muenchen.de/~leisch/Sweave]]で見付けることができます.また,そこには使用例のファイルやFAQに関するlispやシェルの小さなコードがあります.さらに,CompStatの論文やR Newsからミニシリーズの2編の論文(第2/3と第2/3)といったいくつかの論文もあります.


// ** A.2 How can I get Emacs to automatically recognize files in Sweave format? 
** A.2 どのようにしたら Emacs に,Sweave フォーマットのファイルを自動的に認識させられますか? [#h5ecc68f]

// Include something like the following in your .emacs file:
あなたの .emacs ファイルに,つぎのようなコードをいれましょう.

 (defun Rnw-mode ()
   (require 'ess-noweb)
   (noweb-mode)
   (if (fboundp 'R-mode)
       (setq noweb-default-code-mode 'R-mode)))
 (add-to-list 'auto-mode-alist '("\\.Rnw\\'" . Rnw-mode))
 (add-to-list 'auto-mode-alist '("\\.Snw\\'" . Rnw-mode))
 (setq reftex-file-extensions
      '(("Snw" "Rnw" "nw" "tex" ".tex" ".ltx") ("bib" ".bib")))
 (setq TeX-file-extensions
      '("Snw" "Rnw" "nw" "tex" "sty" "cls" "ltx" "texi" "texinfo"))
// The first block of commands makes emacs to automatically load the ESS version of noweb
// mode (with R mode the default code mode) for files with extension .Rnw and .Snw. The last
// two lines make RefTeX work on noweb files. You can download the code from http://www.ci.tuwien.ac.at/~leisch/Sweave/sweave-site.el.
コマンドの最初のブロックは拡張子が .Rnwと .Snw のファイルについてemacs にnoweb モードの ESS バージョンを自動的にロードさせるものです(既定のコードモードは R モード).最後の2行は,RefTex が noweb ファイル上で動くようにするためのものです.コードはhttp://www.ci.tuwien.ac.at/~leisch/Sweave/sweave-site.elでダウンロードできます.


// ** A.3 Can I run Sweave directly from a shell? 
** A.3 Sweave をシェルから直接走らせることはできますか? [#u17d1de9]

// E.g., for writing makefiles it can be useful to run Sweave directly from a shell rather than manually
// start R and then run Sweave. This can easily be done using a simple shell script along the lines of
例えば,makefile を書くなどすると,手動で R を起動してから Sweave を走らせるよりはSweave をシェルから直接走らせるのに便利でしょう.数行の簡単なシェルスクリプトを使うことによって,より簡単にできます.

 #!/bin/sh
 echo "library(tools); Sweave(\"$1\")" | R --no-save --no-restore

// ** A.4 Why does LATEX not find my EPS and PDF graphic files when the filename contains a dot?
** A.4 なぜLaTeXはEPSとPDFファイルがファイル名にドットをふくんでいるときにファイルを見つけてくれないのですか? [#v72d5e81]

// Sweave uses the standard LATEX package graphicx to handle graphic files, which // automatically
// uses EPS files for standard LATEX and PDF files for PDFLATEX, if the name of the input file has
// no extension, i.e., contains no dots. Hence, you may run into trouble with graphics handling if
// the name of your Sweave file contains extra dots: ‘foo.Rnw’ is OK, while ‘foo.bar.Rnw’ is not.
Sweave は,グラフィックファイルを扱うために,標準の LaTeX パッケージである graphicx を使います.それは,もしも入力ファイルの名前が拡張子をもたなければ,つまりドットをふくまなければ,標準の LaTeX には EPS ファイルを,PDFLATEX には PDF ファイルを自動的に使います.したがって,Sweave ファイルの名前が余分なドットをふくんでいた場合,グラフィックスの取扱いの際にトラブルに見舞われることになります.~'foo.Rnw' は大丈夫だが,'foo.bar.Rnw' はダメです.

// **A.5 Why does Sweave by default create both EPS and PDF graphic files? 
**A.5 なぜ Sweave は既定値では EPS と PDF のグラフィックファイルの両方を作成するのですか? [#u8ed65cd]

// The LATEX package graphicx needs EPS files for plain LATEX, but PDF files for // PDFLATEX (the
// latter can also handle PNG and JPEG files). Sweave automatically creates // graphics in EPS and
// PDF format, such that the user can freely run latex or pdflatex on the final // document as needed.
LaTeX のパッケージ graphicx は素の LaTeX のためには EPS ファイルを必要とするが,PDFLATEX のためには PDF を必要とします(後者は PNG と JPEG ファイルも扱うことができます).Sweave は,利用者が最終的なドキュメントで必要に応じてlatex か pdflatex のいずれかを自由に走らせることができるよう,EPS と PDF フォーマットのグラフィクスを自動的に作ります.

// **A.6 Why do R lattice graphics not work?
**A.6 R lattice グラフィックスがなぜ動かないのですか? [#vff91d1c]

// The commands in package lattice have different behavior than the standard plot commands in
// the base package: lattice commands return an object of class "trellis", the actual plotting is
// performed by the print method for the class. Encapsulating calls to lattice functions in print()
// statements should do the trick, e.g.:
lattice パッケージでのコマンドは標準の plot コマンドとはちがうふるまいをします.lattice コマンドは "trellis" クラスのオブジェクトを返し,このクラスでの実際の図の作成は print メソッドで行われます.lattice 関数を print() 宣言の中にくるんで呼び出すことがコツです.つまり,

 <<fig=TRUE>>=
   library(lattice)
   print(bwplot(1:10))
 @

// should work. Future versions of Sweave may have more automated means to deal with trellis
// graphics.
これでうまくいきます.Sweave の将来のバージョンでは trellis グラフィクスを取り扱うためのもっと自動化された方法が取り入れられるでしょう.

// ** A.7 How can I get Black & White lattice graphics?
** A.7 どうすれば白黒の lattice グラフィックスを使えますか? [#aa8653b5]

// What is the most elegant way to specify that strip panels are to have transparent backgrounds
// and graphs are to be in black and white when lattice is being used with Sweave? I would prefer a
// global option that stays in effect for multiple plots.
// Answer by Deepayan Sarkar: I’d do something like this as part of the initialization:
lattice を Sweave で使うときに,分割されたパネルが透明の背景と白黒のグラフをもつように指定するもっともエレガントな方法などんなものでしょう.わたしは複数のプロットに影響をもちつづけるグローバルオプションが好きです.Deepayan Sarkar 氏の答は,初期化のどこかでこのようなことをしています.

 <<...>>
   library(lattice)
   ltheme <- canonical.theme(color = FALSE) ## in-built B&W theme
   ltheme$strip.background$col <- "transparent" ## change strip bg
   lattice.options(default.theme = ltheme) ## set as default
 @

// ** A.8 Creating several figures from one figure chunk does not work
** A.8 ひとつのフィギュアチャンクからいくつかの図を作りたいのだが,できない [#bbef47a5]
// Consider that you want to create several graphs in a loop similar to
つぎのようなループの中でいくつかの図を作りたいとしましょう.
 <<fig=TRUE>>
 for (i in 1:4) plot(rnorm(100)+i)
 @
// This will currently not work, because Sweave allows only one graph per figure chunk. The
// simple reason is that Sweave opens a postscript device before executing the code and closes it
// afterwards. If you need to plot in a loop, you have to program it along the lines of
現在のところこれはまだうまくいきません.というのは,Sweave はひとつのフィギュアチャンクあたりひとつのグラフしか通さないからです.Sweave はコードを実行する前にポストスクリプトデバイスを開いて,あとでそれを閉じるから,というのがその簡単な理由です.もしもループの中でプロットすることが必要ならば,つぎのようにプログラムするとよいでしょう.
 <<results=tex,echo=FALSE>>=
 for(i in 1:4){
 file=paste("myfile", i, ".eps", sep="")
 postscript(file=file, paper="special", width=6, height=6)
 plot(rnorm(100)+i)
 dev.off()
 cat("\\includegraphics{", file, "}\n\n", sep="")
 }
 @

// ** A.9 How can I place all those auto-generated graphics files in a subdirectory rather than the same directory as the Sweave file?
** A.9 どうしたら自動的に生成されたグラフィクスファイルを Sweave ファイルと同じではなく別のサブディレクトリに置くことができますか? [#k11335f6]

// After
まず,
 \SweaveOpts{prefix.string=foo/bar}
// Sweave will place all figures in subdirectory foo and their name will start with bar (instead of the
// name of the Sweave file). The subdirectory foo should exist before you run Sweave.
という風にすると,Sweave はすべての図をfoo というサブディレクトリに置き,その名前は bar で始まります(Sweave ファイルの名前ではなく).サブディレクトリ foo は Sweave が起動される前に存在していなければなりません.

// ** A.10 How can I set default par() settings for figure chunks?
** A.10 どうすればフィギュアチャンクに par() の既定値をセットできますか? [#r4601c0e]

// Because each EPS and PDF file opens a new device, using par() has only an effect if it is used
// inside a figure chunk. If you want to use the same settings for a series of figures, it is easier to use
// a hook function than repeating the same par() statement in each figure chunk.
// The effect of
EPS も PDF ファイルも新しいデバイスを開くので,par() を使ってもその効果はそれが使われたフィギュアチャンクの中でしかありません.同じ設定をいくつもの図に使いたいときには,hook 関数を使う方が,同じ par() 宣言をそれぞれのフィギュアチャンクの中で何度も使うよりも簡単でしょう.
 options(SweaveHooks=list(fig=function() par(bg="red", fg="blue")))
// should be easy to spot. Do not forget to remove the hook at the end of the Sweave file unless you
// want to use it as a global option for all Sweave files.
の効果はすぐわかるでしょう.すべての Sweave ファイルにたいして全域的なオプションとして使いたいのでなければ,Sweave ファイルの最後でフックを外すのを忘れないようにしましょう.

// ** A.11 Running latex fails on Windows
** A.11 Windows で latex ファイルを走らせる [#jd34d2b5]

// If you can create the ‘.tex’ file by running Sweave() in R, but cannot convert the ‘.tex’ file to
// ‘.dvi’ or ‘.pdf’, this is most likely caused by a space in the path of your R installation. If the path
// of your R installation contains any blank characters (like the default "c:\Program Files\..."
// in English versions of Windows), this may cause problems, because programs like tex or latex
// cannot handle blanks in paths properly.
// Two possible solutions:
// 1. Install R in a path not containing any blanks.
// 2. Copy the file ‘Sweave.sty’ to a directory in your tex path or the directory containing the
// Sweave file and put a \usepackage{Sweave} into the preamble of your Sweave file.
R の中で Sweave() を走らせることで '.tex' ファイルを作ったとしても,'.tex' ファイルを '.dvi' や '.pdf' ファイルに変換できないとしたら,それは R をインストールしたパスの場所の問題であることが多いでしょう.もしも R をインストールしたパスが空白文字をふくんでいると(Windows の英語バージョンのように既定値は "\Program Files\..."),tex や latex のようなプログラムはパスの中の空白文字を適切に取り扱うことができないので,問題を引き起こすでしょう.
ふたつの解決方法があります.~
1: R を,空白文字のふくまれていないパスにインストールする,~
2: 'Sweave.sty' を tex のパスか Sweave ファイルをふくんでいるディレクトリにコピーし,Sweave ファイルのプリアンブルに\usepackage{Sweave} を書き込む.

// ** A.12 How can I change the formatting of S input and output chunks? 
** A.12 どうすれば S インプットとアウトプットのチャンクのフォーマットを変えられますか? [#d219d729]

// Sweave uses the fancyvrb package for formatting all S code and text output. fancyvrb is a very
// powerful and flexible package that allows fine control for layouting text in verbatim environments.
// If you want to change the default layout, simply read the fancyvrb documentation and modify
// the definitions of the Sinput and Soutput environments in \u2018Sweave.sty\u2019, respectively.
Sweave はすべての S コードの出力のフォーマットをするためにfancyvrb パッケージを使っています.fancyvrb は verbatim 環境でのテキストのレイアウトを細かく調整できるとてもパワフルで柔軟なパッケージです.もしも既定のレイアウトを変えたければ,ただ fancyvrb のドキュメントを読んで,'Sweave.sty' のなかのSinput と Soutput 環境の定義をそれぞれ変更すればよいだけです.

// ** A.13 How can I change the line length of S input and output?
** A.13 どうすれば S インプットとアウトプットの1行の長さを変えられますか? [#qb033fdd]

// Sweave respects the usual way of specifying the desired line length in S, namely options(width).
// E.g., after options(width=40) lines will be formatted to have at most 40 characters (if possible).
Sweave は,S における,望みの行の長さを指定する通常のやりかた,つまり option(width) を尊重します.例えば,option(width=40) のあとでは,行は最大で 40 文字であるように(可能であれば)フォーマットされます.

// ** A.14 Why are chunks with eval=FALSE executed by R CMD check?
** A.14 eval=FALSE をふくむチャンクはなぜ R CMD チェックによって実行されるのですか? [#g9e80ce4]

// This is a feature, not a bug. From the \u201cWriting R Extensions\u201d manual:
// Package vignettes found in directory inst/doc are tested by R CMD check by executing
// all R code chunks they contain to ensure consistency between code and documentation.
// Note that even code chunks with option eval=FALSE are tested, if you want code in a
// vignette that should not be tested, move it to a normal LATEX verbatim environment.
// The reason for this policy is that users should be able to rely on code examples to be
// executable as seen in the vignette.
これは仕様であってバグではありません."Writing R Extensions"マニュアルによれば,inst/doc ディレクトリにふくまれる小さなパッケージは,コードとドキュメントの整合性を確かめるためにすべての R コードチャンクを実行することによってR CMD チェックによってチェックされます.eval=FALSEのオプションを持つコードチャンクがテストされても,テストされたくないコードの部分があれば,それは通常の LaTeX の verbatim 環境へ移すべきであることに注意が必要です.この考え方の理由は,コードの例が,そのコード断片が見える通りに実行可能であることを保証することが出来るようにするためです.

// ** A.15 Can I use Sweave for HTML files?

// Package R2HTML provides a driver for using Sweave in combination with HTML rather than LATEX.
** A.15 Sweave を HTML ファイルに使えますか?  [#eeb8f1ef]

R2HTML パッケージは,LaTeX ではなく HTML との組合せで Sweave を使えるようにするドライバーを提供します.


// ** A.16 After loading package R2HTML Sweave doesn\u2019t work properly!
** A.16 R2HTML パッケージをロードすると Sweave がちゃんと走りません! [#je001a72]

// Package R2HTML registers an Sweave driver for HTML files, and after that the Syntax for HTML
// is in the search list before the default syntax.
R2HTML パッケージはHTML ファイルのための Sweave ドライバーを登録し,すると,サーチリストのなかで HTML の文法が既定の文法の前に入ります.
 options(SweaveSyntax="SweaveSyntaxNoweb")
//or calling Sweave like
または,Sweave をつぎのように呼ぶことで,R2HTML をロードしたあとでも既定の文法がちゃんと使えるようになります.
 Sweave(..., syntax="SweaveSyntaxNoweb")
//ensures the default syntax even after loading R2HTML.

// * References
* 文献 [#k56ec2e5]

 Richard A. Becker, John M. Chambers, and Allan R. Wilks. The New S Language.
   Chapman & Hall, London, UK, 1988.
 John M. Chambers. Programming with data: A guide to the S language. 
   Springer Verlag, Berlin, Germany, 1998.
 Friedrich Leisch. Sweave: Dynamic generation of statistical reports using 
   literate data analysis.
   In Wolfgang Hrdle and Bernd Rnz, editors, Compstat 2002 \u2014 Proceedings in 
   Computational Statistics, pages 575\u2013580. Physika Verlag, Heidelberg, 
   Germany, 2002. URL http://www.ci.tuwien.ac.at/~leisch/Sweave. 
   ISBN 3-7908-1517-9.
 R Development Core Team. R: A language and environment for statistical 
   computing, 2002. URL http://www.R-project.org. version 1.6.1.
 Norman Ramsey. Noweb man page. University of Virginia, USA, 1998. URL 
   http://www.cs.virginia.edu/~nr/noweb. version 2.9a.
 Anthony J. Rossini, Richard M. Heiberger, Rodney Sparapani, Martin M¨achler, 
   and Kurt Hornik.
   Emacs speaks statistics: A multi-platform, multi-package development 
   environment for statistical analysis. 
   Journal of Computational and Graphical Statistics, 2003. 
   (Accepted for publication).
 Richard M. Stallman. The Emacs Editor. Free Software Foundation, 
   Boston, MA, USA, 1999. URL http://www.gnu.org. version 20.7.
 William N. Venables and Brian D. Ripley. S Programming. Springer, 2000.

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS