裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

Sweave-10

2011年10月14日 | RとLaTeX

xtable と print.xtable の組み合わせで表を書くというのも,長ったらしいオプションであるとか,標準と違うデフォルトとかいうことで,これもまたラッパー関数を書くしかないかなと言うことで以下のようなものを作る。

ytable <- function(x, caption, label, align=NULL, digits=NULL, display=NULL,
                         table.placement="htbp", caption.placement="top",
                         math.style.negative=TRUE )
{
    library(xtable)
    xtable:::print.xtable(xtable(x, caption=caption, label=label, align=align, digits=digits, display=display),
                         table.placement=table.placement, caption.placement=caption.placement,
                         math.style.negative=math.style.negative)
}

.Rnw で

ytable(iris[1:10,], "iris data", "sss")

とか

x <- 1:10
y <- rnorm(10)
ytable(lm(y~x), caption="aaaaa", label="qqq")

caption と label は必須。もし,print.xtable の引数でデフォルトにしたいあるいはデフォルト値を変えたいものがあれば,この関数で定義しておく。


コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Sweave-9

2011年10月14日 | RとLaTeX

図をフロートにする方法はSweave-3 に書いたが,\begin{figure} から始まる一連の指示を毎回書くのは面倒くさい。

表は xtable でそのままフロートになるのだから xtable のような関数を書いてやればよい。

xfigure <- function(fn, caption, label, location="htbp")
{
    cat(sprintf("\\begin{figure}[%s]\n", location))
    cat("\t\\centering\n")
    cat(sprintf("\t\\includegraphics{%s}\n", sub(".(pdf|PDF)", "", fn)))
    cat(sprintf("\t\\caption{%s}\n", caption))
    cat(sprintf("\t\\label{%s}\n", label))
    cat("\\end{figure}\n")
}

これを .Rnw で以下のように使う。

<<results=tex, echo=false>>=
fn <- "test.pdf"
pdf(fn, width=3, height=2, onefile=FALSE)
hist(rnorm(10000))
invisible(dev.off()) # invisible にするか,結果を何かに代入するかしないと余計な文字列が出力される
xfigure(fn, "ヒストグラム", "lab1")
@

毎回 invisible(dev.off()) と書くのが面倒なら,dev.off2 <- function invisible(dev.off()) とでもしておく。

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村