Tips of R

私個人のためだけの備忘録です。ここの情報を参照する場合は、自己責任でお願いします。ほとんど全ての記事はRjpWikiに転記・移動しています。ここにあるのは残りカスです。

pdf()とCairoPDF()
ソースコードの印刷
a2ps
hightlight
PSfrag.sty
gnomeGUI
R Commander のインストール
installation of RGnumeric
パッケージの操作
ミラーサーバを選択しないようにする
追加パッケージをなんでもかんでも追加する
更新できるパッケージのリストの取得
Rの引越
CRAN以外のリポジトリ
ユーザ権限でパッケージを入れる
color.rampの使い方
system()の活用
日付入りのファイル名を作成
PNG ファイルの最適化
CSVファイルのコメント行を確認
月名の文字列を逆順にする
Booktabs
疫学関連パッケージ
PDF出力
外部エディタでオブジェクトの編集
スライド作成
オブジェクトに格納された文字列をオブジェクトの名前にする
画像のはめ込み
シンボル
日本語フォント
ローケルの種類
日本語と特殊文字の混在
HelveticaとGothicBBBの混在
OpenOffice.orgとの連携
オリジナルのフォントを使う
PostScriptを取り込む
Cairoとnon-Cairo
インタプリタ
SVG
Install.packages()
Uwe Ligges
プログレスバー
gonzui
MacOSX

pdf()とCairoPDF()

> library(Cairo)
> CairoFonts(regular="VL-Gothic-Regular:style=Medium",bold="VL-Gothic-Regular:style=Bold")
> CairoPDF(file="/tmp/tmp1.pdf")
> plot(runif(10),runif(10),main="This is 日本語")
> dev.off()
null device
          1
> pdf(file="/tmp/tmp2.pdf",family="Japan1GothicBBB")
> plot(runif(10),runif(10),main="This is 日本語")
> dev.off()
null device
          1

それぞれのPDFのフォントは下記の通り。

$ pdffonts tmp1.pdf
name                                 type              emb sub uni object ID
------------------------------------ ----------------- --- --- --- ---------
IPAMonaPGothic                       CID TrueType      yes no  yes      5  0
IPAMonaPGothic                       CID TrueType      yes no  yes      6  0
$ pdffonts tmp2.pdf
name                                 type              emb sub uni object ID
------------------------------------ ----------------- --- --- --- ---------
ZapfDingbats                         Type 1            no  no  no       9  0
GothicBBB-Medium                     CID Type 0        no  no  no      10  0
GothicBBB-Medium,Bold                CID Type 0        no  no  no      11  0
GothicBBB-Medium,Italic              CID Type 0        no  no  no      12  0
GothicBBB-Medium,BoldItalic          CID Type 0        no  no  no      13  0
Symbol                               Type 1            no  no  no      14  0

CairoPDF()では、IPAMonaPGothicが埋め込まれている。ファイルサイズはtmp1.pdfの方が0.7K多い。CairoFonts()で、regularとboldしか指定しなかったので、italic、bolditalic、symbolが埋め込まれていない。

pdf()の出力 CairoPDF()の出力

ソースコードの印刷

UNIX印刷の場合は、ソースコードをPostScriptに整形しながら変換し、そのPostScriptをプリンタへ送るのが普通であり、テキストファイルをPostScriptに変換するプログラムは旧来からa2psが使われていた。 それを日本語に拡張したa2psjや、ユニコードに対応したu2psなどがある。

a2ps

a2ps用にS言語スタイルファイル s.ssh が用意されている。 これを用いてRのソースコードを構文強調する。

 $ LANG=C
a2ps --pretty-print=s --highlight-level=heavy -o tmp.ps
/usr/lib/R/library/MASS/R-ex/OME.R 

結果は下記の通り、構文に色つけができない。色で構文強調できるenscriptはR用のスタイルがない。 LANG=C をつけないと、日付部分が文字化けする。

hightlight

highlight はソースコードを強調構文して、いろいろな形式で出力するプログラム

$ highlight -M -S r /usr/lib/R/library/MASS/R-ex/OME.R

256色の端末(xterm)に出力するオプション( -M )、スタイルは r を指定すると下記のようになる。

スクリーンキャプチャはGNOMEの端末(gnome-termial)のもの。

$ highlight -G -S r -o tmp.svg /usr/lib/R/library/MASS/R-ex/OME.R

SVG画像に出力することもできる( -G オプション)。

$ highlight -R -S r -o tmp.rtf  /usr/lib/R/library/MASS/R-ex/OME.R

rtfにも出力できる( -R オプション)。出力されたrtfファイルをOpenOffice.orgで表示したところ。

その他、highlightは、HTML、LaTeX、XHTML、XMLなどを出力できる。構文強調の処理を行った後、印刷すればよい。

PSfrag.sty

図に数式を使いたい場合は、Rグラフィック上で数式をTeX形式で書く(例 \tex{$\beta_0$})。次に、出力するときに、カーニングを切っておく。デフォルトではuseKerning=TRUEになっている。

> plot(runif(10),runif(10),xlab="\\tex{$\\beta_0$}",ylab="")
> dev.copy2eps(file="sample.eps",useKerning=FALSE) X11cairo 2
\documentclass{jarticle}
\usepackage{psfrag,graphicx}
\begin{document}
\begin{center}
 \psfragscanon
 \includegraphics[width=\textwidth]{sample.eps}
\end{center}
\end{document}

useKerning=FALSEを省略すると、x軸には\tex{$\beta_0$}と表示される。これは、カーニングが有効だと、epsの中でお節介にTeX命令をを分断してくれるからである。

gnomeGUI

libglade2ではコンパイルできない

R Commander のインストール

installation of RGnumeric

$ LANG=C GNUMERIC_DIR=/home/umusus/rpm/SOURCES/gnumeric-1.0.12/src sudo R  CMD INSTALL RGnumeric_0.3-5.tar.gz
To install the R-Gnumeric plugin, you must have R compiled as a shared library
Reconfigure and compile the R distribution to create R_HOME/bin/libR.so
Use the commands
    configure --enable-R-shlib ...
    make

パッケージの操作

ミラーサーバを選択しないようにする

Rを起動してパッケージの操作をするたびに、どのミラーサーバにしますかとTcl/Tkのウインドウが表示される。いちいち選択するのは面倒なので、 .Rprofile に options(repos=c(CRAN="http://www.stats.bris.ac.uk/R"),papersize="a4") などを追加する。後から変更したくなった場合は、 chooseCRANmirror() を使う。

追加パッケージをなんでもかんでも追加する

インストール可能なパッケージのリストを作成し、それをもとにインストールする。

> pkgs <- available.packages(contriburl="http://cran.md.tsukuba.ac.jp/src/contrib")
> install.packages(pkgs[,1],repos="http://cran.md.tsukuba.ac.jp/")

更新できるパッケージのリストの取得

インストール可能なパッケージのリスト取得には、 available.packages() を使うが、一方、すでにインストールしているがバージョンアップにより更新可能なパッケージのリストを得るには、 old.packages() を使う。

> old.packages()
              Package         LibPath                         Installed Built
IDPmisc       "IDPmisc"       "/usr/local/lib/R/site-library" "0.9.9"   "2.8.0"
ISwR          "ISwR"          "/usr/local/lib/R/site-library" "2.0-2"   "2.7.1"
R2WinBUGS     "R2WinBUGS"     "/usr/local/lib/R/site-library" "2.1-12"  "2.8.1"
RGtk2         "RGtk2"         "/usr/local/lib/R/site-library" "2.12.8"  "2.8.1"
RMySQL        "RMySQL"        "/usr/local/lib/R/site-library" "0.7-3"   "2.8.1"
XML           "XML"           "/usr/local/lib/R/site-library" "1.99-0"  "2.8.1"
ade4          "ade4"          "/usr/local/lib/R/site-library" "1.4-10"  "2.8.0"
bigmemory     "bigmemory"     "/usr/local/lib/R/site-library" "2.3"     "2.8.0"
car           "car"           "/usr/local/lib/R/site-library" "1.2-12"  "2.8.1"
deldir        "deldir"        "/usr/local/lib/R/site-library" "0.0-7"   "2.7.1"
epiR          "epiR"          "/usr/local/lib/R/site-library" "0.9-14"  "2.8.1"
gWidgets      "gWidgets"      "/usr/local/lib/R/site-library" "0.0-32"  "2.8.0"
gWidgetsRGtk2 "gWidgetsRGtk2" "/usr/local/lib/R/site-library" "0.0-50"  "2.8.1"
geoR          "geoR"          "/usr/local/lib/R/site-library" "1.6-23"  "2.8.0"
geoRglm       "geoRglm"       "/usr/local/lib/R/site-library" "0.8-24"  "2.8.1"
grImport      "grImport"      "/usr/local/lib/R/site-library" "0.4-1"   "2.8.1"
igraph        "igraph"        "/usr/local/lib/R/site-library" "0.5.1"   "2.8.0"
magic         "magic"         "/usr/local/lib/R/site-library" "1.4-3"   "2.8.1"
maptools      "maptools"      "/usr/local/lib/R/site-library" "0.7-19"  "2.8.1"
plotrix       "plotrix"       "/usr/local/lib/R/site-library" "2.5-1"   "2.8.1"
rgl           "rgl"           "/usr/local/lib/R/site-library" "0.82"    "2.8.1"
sem           "sem"           "/usr/local/lib/R/site-library" "0.9-15"  "2.8.1"
spam          "spam"          "/usr/local/lib/R/site-library" "0.15-2"  "2.8.0"
spatstat      "spatstat"      "/usr/local/lib/R/site-library" "1.14-10" "2.8.1"
spgrass6      "spgrass6"      "/usr/local/lib/R/site-library" "0.5-18"  "2.8.1"
xtable        "xtable"        "/usr/local/lib/R/site-library" "1.5-4"   "2.8.0"
mapdata       "mapdata"       "/usr/lib/R/site-library"       "2.0-23"  "2.8.0"
maps          "maps"          "/usr/lib/R/site-library"       "2.0-40"  "2.7.0"
survival      "survival"      "/usr/lib/R/library"            "2.35-3"  "2.8.1"
              ReposVer  Repository
IDPmisc       "1.1.00"  "http://cran.md.tsukuba.ac.jp/src/contrib"
ISwR          "2.0-4"   "http://cran.md.tsukuba.ac.jp/src/contrib"
R2WinBUGS     "2.1-14"  "http://cran.md.tsukuba.ac.jp/src/contrib"
RGtk2         "2.12.10" "http://cran.md.tsukuba.ac.jp/src/contrib"
RMySQL        "0.7-4"   "http://cran.md.tsukuba.ac.jp/src/contrib"
XML           "2.3-0"   "http://cran.md.tsukuba.ac.jp/src/contrib"
ade4          "1.4-11"  "http://cran.md.tsukuba.ac.jp/src/contrib"
bigmemory     "3.5"     "http://cran.md.tsukuba.ac.jp/src/contrib"
car           "1.2-13"  "http://cran.md.tsukuba.ac.jp/src/contrib"
deldir        "0.0-8"   "http://cran.md.tsukuba.ac.jp/src/contrib"
epiR          "0.9-15"  "http://cran.md.tsukuba.ac.jp/src/contrib"
gWidgets      "0.0-35"  "http://cran.md.tsukuba.ac.jp/src/contrib"
gWidgetsRGtk2 "0.0-51"  "http://cran.md.tsukuba.ac.jp/src/contrib"
geoR          "1.6-25"  "http://cran.md.tsukuba.ac.jp/src/contrib"
geoRglm       "0.8-25"  "http://cran.md.tsukuba.ac.jp/src/contrib"
grImport      "0.4-2"   "http://cran.md.tsukuba.ac.jp/src/contrib"
igraph        "0.5.2"   "http://cran.md.tsukuba.ac.jp/src/contrib"
magic         "1.4-4"   "http://cran.md.tsukuba.ac.jp/src/contrib"
maptools      "0.7-22"  "http://cran.md.tsukuba.ac.jp/src/contrib"
plotrix       "2.5-4"   "http://cran.md.tsukuba.ac.jp/src/contrib"
rgl           "0.84"    "http://cran.md.tsukuba.ac.jp/src/contrib"
sem           "0.9-16"  "http://cran.md.tsukuba.ac.jp/src/contrib"
spam          "0.15-4"  "http://cran.md.tsukuba.ac.jp/src/contrib"
spatstat      "1.15-2"  "http://cran.md.tsukuba.ac.jp/src/contrib"
spgrass6      "0.6-4"   "http://cran.md.tsukuba.ac.jp/src/contrib"
xtable        "1.5-5"   "http://cran.md.tsukuba.ac.jp/src/contrib"
mapdata       "2.1-0"   "http://cran.md.tsukuba.ac.jp/src/contrib"
maps          "2.1-0"   "http://cran.md.tsukuba.ac.jp/src/contrib"
survival      "2.35-4"  "http://cran.md.tsukuba.ac.jp/src/contrib"

Rの引越

別のPCに同じ環境を作成する場合、または、 Rの再インストールなどで最初からパッケージを入れ直す場合、 事前にパッケージリストを作成しておけば、 楽にパッケージのインストール作業ができる。1つ1つ確認作業、 インストール作業を行うのは面倒だ。cv viewを使う方法もある。

すでにインストールされているパッケージの一覧は下記のようにcsvファイルとして保存すればよいだろう。

> l <- library()
>  write.csv(l$results,file="plist.csv")

新しい環境で、このcsvファイルを読み込み、 install.packages() の引数にパッケージリストを設定すればよい。

CRAN以外のリポジトリ

rSpatial <- "http://r-spatial.sourceforge.net/R"
install.packages("spgwr", repos=rSpatial)

ユーザ権限でパッケージを入れる

ミラーサーバを指定しておく

$ cat .Rprofile
options(repos="http://cran.md.tsukuba.ac.jp")

環境変数を指定しておく

$ cat .Renviron
R_LIBS=~/R/library

Rを起動してホームディレクトリのライブラリ置き場が有効になっているかどうか確認する。

> .libPaths()
[1] "~/R/library"              "/usr/local/lib/R/library"

インストール作業

> install.packages("spdep",lib="~/R/library")

確認する

> library()
Packages in library '~/R/library':

maptools                tools for reading and handling shapefiles
sp                      classes and methods for spatial data
SparseM                 Sparse Linear Algebra
spdep                   Spatial dependence: weighting schemes,
                        statistics and models

Packages in library '/usr/local/lib/R/library':

base                    The R Base Package
[以下略]

color.rampの使い方

color.ramp(nclass,color='red',nvec=NULL,lang='q') nclassは色数 colorは基本色 nvecはrampを作成するための数値ベクトルや因子 typeは区分法、qはquantiles、eはequal-sized

color.ramp()は内部的にcut()を利用して階級区分を作成する。

plot.Map()を実行する前に階級区分を作成することが推奨されている。

fg=cols[findInterval(x=nvec, vec=breaks, all.inside=TRUE)]

RColorBrewerにカラーパレットが入っている。

system()の活用

Rのスクリプトに全ての処理が収まっている方が、処理の管理が楽である。

日付入りのファイル名を作成

paste("hoge-",system("date +%Y%m%d",intern = TRUE),".png",sep="")
[1] "hoge-20060720.png"

これを応用すると、

(a <- paste("hoge-",system("date +%Y%m%d",intern = TRUE),".png",sep=""))
png(a)
plot(rnorm(10),rnorm(10))
dev.off()

これでhoge-20060720.pngという画像ファイルが出力される。

追記(2008年 2月 25日 月曜日 16:45:20 JST)

paste() にベクトルを与えると、ベクトルの要素が連結されるのではなく、 ベクトルで出力される。 Sys.time()format() を組み合わせて、 日付文字列を得ることができる。

> paste(format(Sys.time(), "%Y%m%d"),"-",1:6,".pdf",sep='')
[1] "20080225-1.pdf" "20080225-2.pdf" "20080225-3.pdf" "20080225-4.pdf"
[5] "20080225-5.pdf" "20080225-6.pdf"

PNG ファイルの最適化

pngcrushを使ってRから出力したPNGファイルを最適化する。

> system("pngcrush hoge-20060720.png hoge-20060720-1.png")
 | pngcrush 1.5.10, Copyright (C) 1998-2002 Glenn Randers-Pehrson
 | This is a free, open-source program.  Permission is irrevocably
 | granted to everyone to use this version of pngcrush without
 | payment of any fee.
 | Executable name is pngcrush
 | It was built with libpng version 1.2.8, and is
 | running with  libpng version 1.2.8 - December 3, 2004 (header)
 |    Copyright (C) 1998-2002 Glenn Randers-Pehrson,
 |    Copyright (C) 1996, 1997 Andreas Dilger,
 |    Copyright (C) 1995, Guy Eric Schalnat, Group 42 Inc.,
 | and zlib version 1.1.4, Copyright (C) 1998,
 |    Jean-loup Gailly and Mark Adler.

   Recompressing hoge-20060720.png
   Total length of data found in IDAT chunks   =     2340
   IDAT length with method   1 (fm 0 zl 4 zs 0)=     3858
   IDAT length with method   2 (fm 1 zl 4 zs 0)=     3271
   IDAT length with method   3 (fm 5 zl 4 zs 1)=     2654
   IDAT length with method   9 (fm 5 zl 2 zs 2)=    29316
   IDAT length with method  10 (fm 5 zl 9 zs 1)=     2086
   Best pngcrush method = 10 for hoge-20060720-1.png (10.52% reduction)

   CPU time used = 0.090 seconds (decoding 0.000,
          encoding 0.070, other 0.020 seconds)
> system("ls -lh hoge*.png")
-rw-r--r--    1 hoge hoge       2.1k Jul 20 16:23 hoge-20060720-1.png
-rw-r--r--    1 hoge hoge       2.4k Jul 20 15:54 hoge-20060720.png

ファイルサイズを比べると0.3kほど小さくなった。

CSVファイルのコメント行を確認

read.csv()でskipするCSVファイルのコメント行の行数を確認する。

> system("head test.csv")
# This is test
# July 20, 2006
"ID","name","X"
1,"January",-0.160650805266174
2,"February",-0.341130343325078
3,"March",-0.636784992356978
4,"April",-1.21331355036859
5,"May",-1.18528805527993
6,"June",-0.85074601745131
7,"July",-0.737462268988155

これで2行をスキップすればよいことが分かる。

月名の文字列を逆順にする

> m <- month.name
> write.table(m, file="tmp.txt", row.names = FALSE, quote = FALSE, col.names = FALSE)
> c.rev <- system("rev tmp.txt", intern=TRUE)
> c.rev
 [1] "yraunaJ"   "yraurbeF"  "hcraM"     "lirpA"     "yaM"       "enuJ"
 [7] "yluJ"      "tsuguA"    "rebmetpeS" "rebotcO"   "rebmevoN"  "rebmeceD"

Booktabs

x <- cbind(month.name[1:10],rainbow(10),runif(10))
colnames(x) <- c('Month','Color','x')
library(Hmisc)
latex(x, file="", booktabs=TRUE)

tabularではなくlongtableにしたいときには、longtable=TRUEにする。 fileを空にしないと、ファイル出力され、 latexでコンパイルされてxdviで表示される。 latexVerbatim()は標準出力は不可でファイルに出力され、単純に \begin{verbatim}\end{verbatim}でオブジェクトを囲ったものが出力される。 そのかわり#がそのまま表示できる。

Hmiscのlatex()以外にも、xtableのxtable()がある。booktabsはないみたいだ けど。。。

      \begin{small}
      \setlongtables
      \begin{longtable}{
      <<results=tex,fig=FALSE>>=
      cat(paste(c('c', rep('cc', 34/2-1), 'c'), collapse='@{\hspace{2pt}}'))
      @
      }
      \hline
      \endhead
      \hline
      \endfoot
      <<results=tex,fig=FALSE>>=
      library(xtable)
      set.seed(2345)
      res <- matrix(sample(0:9, size=34*90, replace=TRUE), ncol=34, nrow=90)
      xres <- xtable(res)
      digits(xres) <- rep(0, 35)
      addtorow <- list()
      addtorow$pos <- list()
      addtorow$pos[[1]] <- c(seq(4, 40, 5), seq(49, 85, 5))
      addtorow$pos[[2]] <- 45
      addtorow$command <- c('\vspace{2mm} \n', '\newpage \n')
      print.xtable(xres, add.to.row=addtorow, include.rownames=FALSE, include.colnames=F ALSE, only.contents=TRUE, hline.after=NULL)
      @
      \end{longtable}
      \end{small}

疫学関連パッケージ

PDF出力

問題 RグラフィックをPDF出力するときにもっともよいのはどれか

  1. Rでdev.copy2eps()を使ってepsを出力後にps2pdfで変換
  2. Rでdev.copy2eps()を使ってepsを出力後にps2pdf14で変換
  3. Rでdev.copy2eps()を使ってepsを出力後にepstopdfで変換
  4. Rのpdf()を使った

dev.copy2eps()で出力したepsのBoundingBoxは0 0 504 503 であった。1と2の BoundingBoxは0 0 612 792となっており、余白が増加している。ただし、2は PDF14なのでMediaBoxという名前になっている。このため、 ebbはPDF14以降は扱えない。このBoundingBoxは余白が多く、 ps2pdfのBoundingBoxの扱いが雑であることがわかる。なお、2の方は、 文字化けする。一方、3の場合は、きっちりと BoundingBoxを計算しており、 BoundingBox: 0 0 504 503である。しかし、これをAdobe Readerで表示すると、 天地が逆になっている。 これをLaTeX文書に埋め込むと正しくなっているのは不思議である。4の場合の BoundingBoxは0 0 432 432であり、dev.copy2eps()を使った場合よりも小さい。 余白は、epstopdfを使った場合と同じ。

変換 name type emb sub uni object ID
ps2pdf Helvetica Type 1 no no no 9 0
pdf2pdf14 Helvetica Type 1 no no no 9 0
epstopdf PKUKPU+Helvetica Type 1C yes yes no 10 0
Direct ZapfDingbats Type 1 no no no 5 0
Direct Helvetica Type 1 no no no 10 0

epstopdfのみがフォントを埋め込んでいる。

PDFの基本情報

変換 Producer Tagged Pages Encrypted Page size File size Optimized PDF version
ps2pdf GNU Ghostscript 7.07 no 1 no 612 x 792 pts (letter) 2029 bytes no 1.2
ps2pdf14 GNU Ghostscript 7.07 no 1 no 612 x 792 pts (letter) 3146 bytes no 1.4
epstopdf GNU Ghostscript 7.07 no 1 no 504 x 503 pts 4830 bytes no 1.3
direct R 2.4.1 no 1 no 432 x 432 pts 3215 bytes no 1.1

外部エディタでオブジェクトの編集

z<- c(1,2,3,4)
## Linux
x <- edit(z) #opens vi
x <- edit(z, editor="gnumeric") #opens "z" in gnumeric
x <- edit(z, editor="gedit") #opens "z" in gedit
## Windows
x <- edit(z) #opens z in notepad
x <- edit(z, editor="C:\\Program Files\\Microsoft Office\\Office\\Excel.exe") #opens z in excel

スライド作成

Hmiscのps.slide()を使う。ps.slide()とtopdf()を使うことにより、 スライドに適した線の太さ、フォントのグラフィっすを出力することができる。 また、psfragを使うことにより、 TeXの数式やフォントに置き換えることができる。

オブジェクトに格納された文字列をオブジェクトの名前にする

> DATA <- matrix(1:30,5,6)
> my_name <- sprintf(paste("data","A",sep="_"))
> DATA
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    6   11   16   21   26
[2,]    2    7   12   17   22   27
[3,]    3    8   13   18   23   28
[4,]    4    9   14   19   24   29
[5,]    5   10   15   20   25   30
> my_name
[1] "data_A"
> assign(my_name,DATA)
> data_A
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    6   11   16   21   26
[2,]    2    7   12   17   22   27
[3,]    3    8   13   18   23   28
[4,]    4    9   14   19   24   29
[5,]    5   10   15   20   25   30

画像のはめ込み

シンボル

PostScriptのSymbolフォント

これをRで表示する

> plot(runif(10),runif(10))
> text(0.5,0.5,"\xA9",font=5,cex=3)
> dev.copy2eps(file="symbol-test.eps")

日本語フォント

Japan1 (PS) HeiseiKakuGo-W5 Linotype Japanese printer font
Japan1 (PDF) KozMinPro-Regular-Acro from Adobe Reader 7.0 Japanese Font Pack
Japan1HeiMin (PS) HeiseiMin-W3 Linotype Japanese printer font
Japan1HeiMin (PDF) HeiseiMin-W3-Acro from Adobe Reader 7.0 Japanese Font Pack
Japan1GothicBBB GothicBBB-Medium Japanese-market PostScript printer font
Japan1Ryumin Ryumin-Light Japanese-market PostScript printer font

ローケルの種類

> iconvlist()
> capabilities()
    jpeg      png    tcltk      X11 http/ftp  sockets   libxml     fifo
    TRUE     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE
  cledit    iconv      NLS  profmem
    TRUE     TRUE     TRUE    FALSE
> capabilities("iconv")
iconv
 TRUE
> ps.options()$encoding
[1] "default"
> postscriptFonts()$Japan1GothicBBB
$family
[1] "GothicBBB-Medium"

$metrics
[1] ""           ""           ""           ""           "Symbol.afm"

$cmap
[1] "EUC-H"

$cmapEncoding
[1] "EUC-JP"

$pdfresource
[1] ""

attr(,"class")
[1] "CIDFont"
> names(pdfFonts())
 [1] "serif"                "sans"                 "mono"
 [4] "symbol"               "AvantGarde"           "Bookman"
 [7] "Courier"              "Helvetica"            "Helvetica-Narrow"
[10] "NewCenturySchoolbook" "Palatino"             "Times"
[13] "URWGothic"            "URWBookman"           "NimbusMon"
[16] "NimbusSan"            "URWHelvetica"         "NimbusSanCond"
[19] "CenturySch"           "URWPalladio"          "NimbusRom"
[22] "URWTimes"             "Japan1"               "Japan1HeiMin"
[25] "Japan1GothicBBB"      "Japan1Ryumin"         "Korea1"
[28] "Korea1deb"            "CNS1"                 "GB1"

pdf() だと日本語はOK

> pdf("tmp2.pdf",family="Japan1")
> plot(runif(10),runif(10),main="日本語"); dev.off()
null device
          1
Warning message:
In dev.off() :  PDF のバージョンを 1.3 に更新

Japan1を指定すると

$ pdffonts tmp.pdf
name                                 type         emb sub uni object ID
------------------------------------ ------------ --- --- --- ---------
ZapfDingbats                         Type 1       no  no  no       5  0
KozMinPro-Regular-Acro               CID Type 0   no  no  no      10  0
KozMinPro-Regular-Acro,Bold          CID Type 0   no  no  no      11  0
KozMinPro-Regular-Acro,Italic        CID Type 0   no  no  no      12  0
KozMinPro-Regular-Acro,BoldItalic    CID Type 0   no  no  no      13  0
Symbol                               Type 1       no  no  no      14  0

日本語と特殊文字の混在

> pdf("tmp2.pdf",family="Japan1GothicBBB")
> plot(runif(10),runif(10),main="特殊文字テスト")
> plot(0:2,0:2,main="特殊文字テスト")
> text(1,1,"\xA9",font=5,cex=10,col="red")
> dev.off()
null device
          1
Warning message:
In dev.off() :  PDF のバージョンを 1.3 に更新

pdf() ディバイスでも、Symbolの指定は、 postscript() と同じようだ。

$ pdffonts tmp3.pdf
name                                 type         emb sub uni object ID
------------------------------------ ------------ --- --- --- ---------
ZapfDingbats                         Type 1       no  no  no       5  0
GothicBBB-Medium                     CID Type 0   no  no  no      10  0
GothicBBB-Medium,Bold                CID Type 0   no  no  no      11  0
GothicBBB-Medium,Italic              CID Type 0   no  no  no      12  0
GothicBBB-Medium,BoldItalic          CID Type 0   no  no  no      13  0
Symbol                               Type 1       no  no  no      14  0

HelveticaとGothicBBBの混在

どうやらできないようだ。

OpenOffice.orgとの連携

odfWeaveというパッケージを使う

オリジナルのフォントを使う

CMitalic <- Type1Font("ComputerModern2",
                      c("CM_regular_10.afm", "CM_boldx_10.afm",
                        "cmti10.afm", "cmbxti10.afm",
                        "CM_symbol_10.afm"),
                      encoding = "TeXtext.enc")
postscript(family = CMitalic)
afmfiles <- c("/usr/share/texmf/fonts/afm/yandy/lubright/lbr.afm",
               "/usr/share/texmf/fonts/afm/yandy/lubright/lbd.afm",
               "/usr/share/texmf/fonts/afm/yandy/lubright/lbi.afm",
               "/usr/share/texmf/fonts/afm/yandy/lubright/lbdi.afm",
               "/usr/share/texmf/fonts/afm/yandy/lubright/lbms.afm")
# Set up the mapping for "lucida" font family
postscriptFonts(lucida=postscriptFont("Lucida", metrics=afmfiles))
# Specify that the "lucida" font is to be used
## postscript(file="test.ps", family="lucida");
## par(family="lucida")
postscript(file="test.ps", fonts="lucida");
l<- 40:80;
plot(l,l,pch=l);
dev.off();
?Type1Font

PostScriptを取り込む

There is also an example of how to do this sort of thing using the grImport package (and grid and lattice) in

library(grImport)
hourglass <-
     new("Picture",
         paths=
         list(new("PictureFill",
                  x=c(0, 1, 0, 1),
                  y=c(0, 0, 1, 1),
                  rgb="black"),
              new("PictureStroke",
                  x=c(0, 1, 0, 1, 0),
                  y=c(0, 0, 1, 1, 0),
                  rgb="grey")),
         summary=
         new("PictureSummary",
             numPaths=1,
             xscale=c(0, 1),
             yscale=c(0, 1)))
dotplot(variety ~ yield | year, data=barley,
         panel=function(x, y, type, ...) {
             panel.dotplot(x, y, lang="n", ...)
             grid.symbols(hourglass,
                          x=unit(as.numeric(x), "native"),
                          y=unit(as.numeric(y), "native"),
                          size=unit(5, "mm"))
         })

Cairoとnon-Cairo

 > X11(type="Xlib")
 > system.time(pairs(USJudgeRatings))
   user  system elapsed
  0.176   0.004   0.407
 > system.time(pairs(USJudgeRatings))
   user  system elapsed
  0.836   0.252   2.398

こんなにも処理速度が違うとは。

インタプリタ

littler は小文字のrがコマンド名のRインタープリタ

#!/usr/bin/r
print(pi/2)
pdf(file="tmp.pdf")
plot(runif(10),runif(10))
dev.off()
system('gnome-open tmp.pdf')
$ chmod +x tmp.r
$ ./tmp.r
[1] 1.570796

スクリプトの引数の扱いが簡単

#!/usr/bin/r
if(!is.null(argv)) print(pi/as.numeric(argv))
$ ./tmp.r
$ ./tmp.r 3
[1] 1.047198

日本語の扱い

#!/usr/bin/r
print(paste('こんにちは',argv))
$ ./tmp.r
[1] "こんにちは "
$ ./tmp.r 世界
[1] "こんにちは 世界"
$ ./tmp.r 世界 と 日本
[1] "こんにちは 世界" "こんにちは と"   "こんにちは 日本"

SVG

svgに出力するとinkscapeで編集が容易

Install.packages()

ESSのメーリングリストでinstall.packages()がEmacsの中からうまくいかないという相談があった。 そのときの回答の中で、

chooseCRANmirror(graphics=FALSE)

とすればGUIが抑制されると知った。

Uwe Ligges

『Rの基礎とプログラミング技法』 の著者であるUwe Liggesのチュートリアル(2010年11月27日)で新しく知ったこと

プログレスバー

C言語の解説を見ていて、思いついた。

for(i in 1:20){Sys.sleep(.1);cat(paste(i,"/ 20","\r"),file=stderr())}; cat("finished\n",file=stderr())

キャリッジリターンはそもそも先頭に戻るという意味らしい。それを使うと、こんなことができてします。上下移動などエスケープシークエンスでできるので、かなり複雑なことができる。cat("\x1b[2A",file=stderr())とかもあり。 前景色、背景色もOK。Windowsではエスケープシークエンスはだめみたい。

gonzui

$ sudo apt-get install gonzui
$ gonzui-import http://cran.r-project.org/src/contrib/sp_0.9-76.tar.gz
sp_0.9-76:     100% |oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo| Time: 00:00:03
174 contents of 1 packages imported in 18.13 sec. (9.60 contents / sec.)
$ gonzui-import http://cran.r-project.org/src/base/R-2/R-2.12.1.tar.gz
R-2.12.1:      100% |oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo| Time: 00:03:22
4035 contents of 1 packages imported in 591.11 sec. (6.83 contents / sec.)
$ gonzui-import ineq_0.2-9.tar.gz
ineq_0.2-9:    100% |oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo| Time: 00:00:00
17 contents of 1 packages imported in 1.42 sec. (12.00 contents / sec.)
$ gonzui-server
http://r01:46984/

$ gonzui-search Gini
ineq_0.2-9/R/ineq.R:ineq <- function(x, parameter=NULL, type=c("Gini", "RS", "Atkinson", "Theil",
ineq_0.2-9/R/ineq.R:  Gini = Gini(x),
ineq_0.2-9/R/ineq.R:Gini <- function(x)
ineq_0.2-9/R/ineq.R:    G <- Gini(x2)
ineq_0.2-9/man/Lc.mehran.Rd:\references{F Mehran: Bounds on the Gini Index Based on Observed Points of the Lorenz Curve, 1975, JASA 70, 64-66. }
ineq_0.2-9/man/ineq.Rd:\alias{Gini}
ineq_0.2-9/man/ineq.Rd:ineq(x, parameter = NULL, type = c("Gini", "RS", "Atkinson", "Theil", "Kolm", "var",
ineq_0.2-9/man/ineq.Rd:Gini(x)
ineq_0.2-9/man/ineq.Rd:  is sufficient). defaults to "Gini".}
ineq_0.2-9/man/ineq.Rd:\details{\code{ineq} is just a wrapper for the inequality measures \code{Gini},
ineq_0.2-9/man/ineq.Rd:         \code{Gini} is the Gini coefficient, \code{RS} is the the Ricci-Schutz
ineq_0.2-9/man/ineq.Rd:# compute Gini coefficient

MacOSX

MacOSXにインストールするときは、bdbのバージョンが新しく"Fixnum expected"というエラーが出てgonzuiが機能しない。

$ gonzui-search BibTeX
/opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:578:in `pack_id2': Fixnum expected (TypeError)
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:578:in `get_path_ids_from_package_and_word_id'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:198:in `collect_all_results'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:197:in `each'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:197:in `collect_all_results'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/dbm.rb:357:in `find_all'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/cmdapp/search.rb:101:in `send'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/cmdapp/search.rb:101:in `search'
        from /opt/local/bin/gonzui-search:57:in `do_start'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/cmdapp/app.rb:142:in `start'
        from /opt/local/lib/ruby/site_ruby/1.8/gonzui/cmdapp/app.rb:168:in `start'
        from /opt/local/bin/gonzui-search:64

パッチを公開してくれていつ人がいたのでこれを利用してMacPortsのPortfileを作成する。ひな形は、MacPortsWiki-JPからダウンロード。 ここに公開する。このPortfileをLocalPortsとして登録し、gonzuiをインストールする。

$ sudo port install gonzui
Portfile changed since last build; discarding previous state.
--->  Computing dependencies for gonzui
--->  Fetching gonzui
--->  Verifying checksum(s) for gonzui
--->  Extracting gonzui
--->  Applying patches to gonzui
--->  Configuring gonzui
--->  Building gonzui
--->  Staging gonzui into destroot
--->  Installing gonzui @1.2_0
--->  Activating gonzui @1.2_0
--->  Cleaning gonzui

試しにR-2.12.1.tar.gzでインデックスを作成する。

$ gonzui-import R-2.12.1.tar.gz
R-2.12.1:      100% |oooooooooooooooooooooooooooooooooooooooooo| Time: 00:03:10
4035 contents of 1 packages imported in 194.57 sec. (20.74 contents / sec.)

テキストベースで検索してみる。

$ gonzui-search BibTeX
R-2.12.1/NEWS:      manipulating bibliographic information in enhanced BibTeX style,
R-2.12.1/NEWS:      found by BibTeX.
R-2.12.1/OONEWS:          R objects to BibTeX and LaTeX (but almost no methods yet).
R-2.12.1/doc/NEWS.Rd:        enhanced BibTeX style, unifying and enhancing the previously
R-2.12.1/doc/NEWS.Rd:      are found by BibTeX.
R-2.12.1/doc/html/NEWS.html:enhanced BibTeX style, unifying and enhancing the previously
R-2.12.1/doc/html/NEWS.html:are found by BibTeX.
R-2.12.1/share/texmf/bibtex/bst/jss.bst:%% ** BibTeX style file for JSS publications (http://www.jstatsoft.org/)
R-2.12.1/share/texmf/bibtex/bst/jss.bst: %   For use with BibTeX version 0.99a or later
R-2.12.1/src/library/tools/R/utils.R:        ## BibTeX errors.
R-2.12.1/src/library/tools/R/utils.R:                errors <- paste("BibTeX errors:",
R-2.12.1/src/library/tools/R/utils.R:        ## BibTeX errors.
R-2.12.1/src/library/tools/R/utils.R:                msg <- paste(msg, "BibTeX errors:",
R-2.12.1/src/library/tools/R/utils.R:    ## Get BibTeX error info, using non-header lines until the first
R-2.12.1/src/library/tools/man/bibstyle.Rd:modelled after those used by BibTeX.  This function allows environments
R-2.12.1/src/library/utils/R/citation.R:                                  c("\nA BibTeX entry for LaTeX users is\n",
R-2.12.1/src/library/utils/man/bibentry.Rd:  information in enhanced BibTeX style.
R-2.12.1/src/library/utils/man/bibentry.Rd:  \item{bibtype}{a character string with a BibTeX entry type.
R-2.12.1/src/library/utils/man/bibentry.Rd:  BibTeX (\code{"Bibtex"}),
R-2.12.1/src/library/utils/man/bibentry.Rd:  a mixture of plain text and BibTeX as traditionally used for citations
R-2.12.1/src/library/utils/man/bibentry.Rd:  BibTeX.
R-2.12.1/src/library/utils/man/bibentry.Rd:  after BibTeX entries.  The entry should be a valid BibTeX entry type,
R-2.12.1/src/library/utils/man/bibentry.Rd:  BibTeX fields, including
R-2.12.1/src/library/utils/man/bibentry.Rd:## Convert to BibTeX
R-2.12.1/src/library/utils/man/citEntry.Rd:  BibTeX style.
R-2.12.1/src/library/utils/man/citEntry.Rd:  \item{entry}{a character string with a BibTeX entry type.
R-2.12.1/src/library/utils/man/citation.Rd:  returned by \code{citation()} shows both a text version and a BibTeX
R-2.12.1/src/library/utils/man/citation.Rd:  text versions are shown.  The BibTeX versions can be obtained using
R-2.12.1/src/library/utils/man/person.Rd:  result, the \code{toBibtex()} method creates a suitable BibTeX
R-2.12.1/src/library/utils/man/person.Rd:## Conversion to BibTeX author field.
R-2.12.1/src/library/utils/man/toLatex.Rd:\title{Converting R Objects to BibTeX or LaTeX}
R-2.12.1/src/library/utils/man/toLatex.Rd:  BibTeX or LaTeX markup.
R-2.12.1/src/library/utils/man/toLatex.Rd:  corresponding BibTeX or LaTeX file.
$ gonzui-server
http://MacBookAir.local:46984/


更新:2011年 1月 13日 木曜日 22:04:41 JST  Top