// 谷村晋 2005年  5月 12日 木曜日 16:13:08 JST
// 自分用のメモのようで申し訳ありません
// 自由に修正・加筆してください
// 2006年  7月  5日 水曜日 15:22:57 JST
// 大幅改訂しました(谷村)

COLOR(red){SIZE(30){Rのソースコードを[[LaTeX]]文書に記述する}}

Rのソースコードを[[LaTeX]]文書に記述するには、[[listings.sty:http://www.ring.gr.jp/pub/text/CTAN/macros/latex/contrib/listings/]]を使います。[[listings.sty:http://www.ring.gr.jp/pub/text/CTAN/macros/latex/contrib/listings/]]を使うと、Rソースファイルを構文強調して表示することができます。
R言語の定義は、lstlang3.sty に書かれています。

#contents
----

* [[listings.sty:http://www.ring.gr.jp/pub/text/CTAN/macros/latex/contrib/listings/]]の利用例

listings.styを使うと見出しをつけたり、任意の間隔で行番号をつけたり、さまざまな種類の枠をつけたり、プログラムコードのリスト(目次)を作成したり、いろいろなことができます。ここでは、単純に表示した例を示します。

** 利用例1
まずはデフォルトのままで表示する。
 \documentclass{jsarticle}
 \usepackage{listings}
 \begin{document}
 \begin{lstlisting}[language=R]
  boa.acf <- function(link, lags)
  # Brian Smith has produced the BOA (Bayesian Output Analysis) suite of
  # S-plus/R functions for analysis of MCMC output, which reads in output
  # from Classic BUGS or WinBUGS. Version 0.5.0 is now available.
  {
    pnames <- boa.pnames(link)
    result <- matrix(NA, nrow = ncol(link), ncol = length(lags),
                     dimnames = list(pnames, paste("Lag", lags)))
    lags <- lags[lags <= (nrow(link) - 1)]
    n.lags <- length(lags)
    if(n.lags > 0) {
       idx <- 1:n.lags
       lag.max <- max(lags)
       for(i in pnames) {
          result[i, idx] <- acf(link[, i], lag.max = lag.max,
                                plot = FALSE)$acf[lags + 1]
       }
    }
  
    return(result)
  }
  \end{lstlisting}
 \end{document}

出力結果
&ref(listings01.png,center);

** 利用例2
タイプライタ体にしてみる。デフォルトでは行間が空きすぎなので半分に狭くする。
 \documentclass{jsarticle}
 \usepackage{listings}
 \lstset{%
   language=R,
   basicstyle={\ttfamily},
   breaklines=true,
   columns=[l]{fullflexible},
   lineskip=-0.5zw,
 }
 \begin{document}
 \begin{lstlisting}
  boa.acf <- function(link, lags)
  # Brian Smith has produced the BOA (Bayesian Output Analysis) suite of
  # S-plus/R functions for analysis of MCMC output, which reads in output
  # from Classic BUGS or WinBUGS. Version 0.5.0 is now available.
  {
    pnames <- boa.pnames(link)
    result <- matrix(NA, nrow = ncol(link), ncol = length(lags),
                     dimnames = list(pnames, paste("Lag", lags)))
    lags <- lags[lags <= (nrow(link) - 1)]
    n.lags <- length(lags)
    if(n.lags > 0) {
       idx <- 1:n.lags
       lag.max <- max(lags)
       for(i in pnames) {
          result[i, idx] <- acf(link[, i], lag.max = lag.max,
                                plot = FALSE)$acf[lags + 1]
       }
    }
  
    return(result)
  }
  \end{lstlisting}
 \end{document}

出力結果
&ref(listings02.png,center);

** 利用例3
カラー表示にしてみる。LaTeXでプレゼンテーションスライドを作成するときには、是非ともカラー表示にしたい。

 \documentclass{jsarticle}
 \usepackage[dvips]{color}
 \usepackage{listings}
 \definecolor{Brown}{cmyk}{0,0.81,1,0.60}
 \definecolor{OliveGreen}{cmyk}{0.64,0,0.95,0.40}
 \definecolor{CadetBlue}{cmyk}{0.62,0.57,0.23,0}
 \lstset{%
   language=R,
   stringstyle={\ttfamily},
   commentstyle={\itshape\color{Brown}},
   identifierstyle={\ttfamily\color{CadetBlue}\bfseries}, 
   keywordstyle={\ttfamily\color{OliveGreen}},
   basicstyle={\ttfamily},
   breaklines=true,
   columns=[l]{fullflexible},
   lineskip=-0.5zw,
   showstringspaces=ture
 }
 \begin{document}
 \begin{lstlisting}
 boa.acf <- function(link, lags)
 # Brian Smith has produced the BOA (Bayesian Output Analysis) suite of
 # S-plus/R functions for analysis of MCMC output, which reads in output
 # from Classic BUGS or WinBUGS. Version 0.5.0 is now available.
 {
   pnames <- boa.pnames(link)
   result <- matrix(NA, nrow = ncol(link), ncol = length(lags),
                    dimnames = list(pnames, paste("Lag", lags)))
   lags <- lags[lags <= (nrow(link) - 1)]
   n.lags <- length(lags)
   if(n.lags > 0) {
      idx <- 1:n.lags
      lag.max <- max(lags)
      for(i in pnames) {
         result[i, idx] <- acf(link[, i], lag.max = lag.max,
                               plot = FALSE)$acf[lags + 1]
      }
   }
 
   return(result)
 }
 \end{lstlisting}
 \end{document}

出力結果
&ref(listings03.png,center);

** 利用例4
さらにESS風(VineLinux標準のEmacsカラーテーマにess-modeを読み込んだ感じ)にしてみる。
 \documentclass{jsarticle}
 \usepackage{listings}
 \usepackage[dvips]{color}
 \lstset{%
   language=R,
   frame=shadowbox,
   backgroundcolor={\color[cmyk]{0.777,0.777,0,0.561}},
   stringstyle={\ttfamily\color[cmyk]{0,0.51,0.843,0}},
   commentstyle={\color[cmyk]{0,0.51,0.843,0}},
   identifierstyle={\ttfamily\color{white}}, 
   keywordstyle={\ttfamily\color[cmyk]{1,0,0,0}},
   classoffset=2,
   basicstyle={\ttfamily\color{white}},
   breaklines=true,
   columns=[l]{fullflexible},
   lineskip=-0.5zw,
   morekeywords={FALSE,TRUE,NA},
   keywordstyle={\color[cmyk]{0.371,0,0.371,0.016}},
   classoffset=0,
   morekeywords={<-},
   keywordstyle={\color[cmyk]{0.525,0,0.157,0}},
   classoffset=1,
   numbers=left,
   stepnumber=5,
   numberstyle={\scriptsize\color{black}},
   numbersep=1em,
   xleftmargin=1zw,
   xrightmargin=1zw,
   framerule=2pt,
   rulecolor={\color[gray]{.85}},
 }
 \begin{document}
 \begin{lstlisting}
  boa.acf <- function(link, lags)
  # Brian Smith has produced the BOA (Bayesian Output Analysis) suite of
  # S-plus/R functions for analysis of MCMC output, which reads in output
  # from Classic BUGS or WinBUGS. Version 0.5.0 is now available.
  {
    pnames <- boa.pnames(link)
    result <- matrix(NA, nrow = ncol(link), ncol = length(lags),
                     dimnames = list(pnames, paste("Lag", lags)))
    lags <- lags[lags <= (nrow(link) - 1)]
    n.lags <- length(lags)
    if(n.lags > 0) {
       idx <- 1:n.lags
       lag.max <- max(lags)
       for(i in pnames) {
          result[i, idx] <- acf(link[, i], lag.max = lag.max,
                                plot = FALSE)$acf[lags + 1]
       }
    }
  
    return(result)
  }
  \end{lstlisting}
 \end{document}

出力結果
&ref(listings04.png,center);

色強調するキーワードがess-modeと微妙に違うけれども、このあたりで妥協。


* lstlang3.styにおけるRの定義
Rのキーワードの定義は下記のようになっています。ここにリストされていない単語は、TeXソースの中で適宜追加すれば(つまり、language{R}を再定義する)キーワード扱いになります。

 \lst@definelanguage{R}%
  {keywords={abbreviate,abline,abs,acos,acosh,action,add1,add,%
      aggregate,alias,Alias,alist,all,anova,any,aov,aperm,append,apply,%
      approx,approxfun,apropos,Arg,args,array,arrows,as,asin,asinh,%
      atan,atan2,atanh,attach,attr,attributes,autoload,autoloader,ave,%
      axis,backsolve,barplot,basename,besselI,besselJ,besselK,besselY,%
      beta,binomial,body,box,boxplot,break,browser,bug,builtins,bxp,by,%
      c,C,call,Call,case,cat,category,cbind,ceiling,character,char,%
      charmatch,check,chol,chol2inv,choose,chull,class,close,cm,codes,%
      coef,coefficients,co,col,colnames,colors,colours,commandArgs,%
      comment,complete,complex,conflicts,Conj,contents,contour,%
      contrasts,contr,control,helmert,contrib,convolve,cooks,coords,%
      distance,coplot,cor,cos,cosh,count,fields,cov,covratio,wt,CRAN,%
      create,crossprod,cummax,cummin,cumprod,cumsum,curve,cut,cycle,D,%
      data,dataentry,date,dbeta,dbinom,dcauchy,dchisq,de,debug,%
      debugger,Defunct,default,delay,delete,deltat,demo,de,density,%
      deparse,dependencies,Deprecated,deriv,description,detach,%
      dev2bitmap,dev,cur,deviance,off,prev,,dexp,df,dfbetas,dffits,%
      dgamma,dgeom,dget,dhyper,diag,diff,digamma,dim,dimnames,dir,%
      dirname,dlnorm,dlogis,dnbinom,dnchisq,dnorm,do,dotplot,double,%
      download,dpois,dput,drop,drop1,dsignrank,dt,dummy,dump,dunif,%
      duplicated,dweibull,dwilcox,dyn,edit,eff,effects,eigen,else,%
      emacs,end,environment,env,erase,eval,equal,evalq,example,exists,%
      exit,exp,expand,expression,External,extract,extractAIC,factor,%
      fail,family,fft,file,filled,find,fitted,fivenum,fix,floor,for,%
      For,formals,format,formatC,formula,Fortran,forwardsolve,frame,%
      frequency,ftable,ftable2table,function,gamma,Gamma,gammaCody,%
      gaussian,gc,gcinfo,gctorture,get,getenv,geterrmessage,getOption,%
      getwd,gl,glm,globalenv,gnome,GNOME,graphics,gray,grep,grey,grid,%
      gsub,hasTsp,hat,heat,help,hist,home,hsv,httpclient,I,identify,if,%
      ifelse,Im,image,\%in\%,index,influence,measures,inherits,install,%
      installed,integer,interaction,interactive,Internal,intersect,%
      inverse,invisible,IQR,is,jitter,kappa,kronecker,labels,lapply,%
      layout,lbeta,lchoose,lcm,legend,length,levels,lgamma,library,%
      licence,license,lines,list,lm,load,local,locator,log,log10,log1p,%
      log2,logical,loglin,lower,lowess,ls,lsfit,lsf,ls,machine,Machine,%
      mad,mahalanobis,make,link,margin,match,Math,matlines,mat,matplot,%
      matpoints,matrix,max,mean,median,memory,menu,merge,methods,min,%
      missing,Mod,mode,model,response,mosaicplot,mtext,mvfft,na,nan,%
      names,omit,nargs,nchar,ncol,NCOL,new,next,NextMethod,nextn,%
      nlevels,nlm,noquote,NotYetImplemented,NotYetUsed,nrow,NROW,null,%
      numeric,\%o\%,objects,offset,old,on,Ops,optim,optimise,optimize,%
      options,or,order,ordered,outer,package,packages,page,pairlist,%
      pairs,palette,panel,par,parent,parse,paste,path,pbeta,pbinom,%
      pcauchy,pchisq,pentagamma,persp,pexp,pf,pgamma,pgeom,phyper,pico,%
      pictex,piechart,Platform,plnorm,plogis,plot,pmatch,pmax,pmin,%
      pnbinom,pnchisq,pnorm,points,poisson,poly,polygon,polyroot,pos,%
      postscript,power,ppoints,ppois,predict,preplot,pretty,Primitive,%
      print,prmatrix,proc,prod,profile,proj,prompt,prop,provide,%
      psignrank,ps,pt,ptukey,punif,pweibull,pwilcox,q,qbeta,qbinom,%
      qcauchy,qchisq,qexp,qf,qgamma,qgeom,qhyper,qlnorm,qlogis,qnbinom,%
      qnchisq,qnorm,qpois,qqline,qqnorm,qqplot,qr,Q,qty,qy,qsignrank,%
      qt,qtukey,quantile,quasi,quit,qunif,quote,qweibull,qwilcox,%
      rainbow,range,rank,rbeta,rbind,rbinom,rcauchy,rchisq,Re,read,csv,%
      csv2,fwf,readline,socket,real,Recall,rect,reformulate,regexpr,%
      relevel,remove,rep,repeat,replace,replications,report,require,%
      resid,residuals,restart,return,rev,rexp,rf,rgamma,rgb,rgeom,R,%
      rhyper,rle,rlnorm,rlogis,rm,rnbinom,RNGkind,rnorm,round,row,%
      rownames,rowsum,rpois,rsignrank,rstandard,rstudent,rt,rug,runif,%
      rweibull,rwilcox,sample,sapply,save,scale,scan,scan,screen,sd,se,%
      search,searchpaths,segments,seq,sequence,setdiff,setequal,set,%
      setwd,show,sign,signif,sin,single,sinh,sink,solve,sort,source,%
      spline,splinefun,split,sqrt,stars,start,stat,stem,step,stop,%
      storage,strstrheight,stripplot,strsplit,structure,strwidth,sub,%
      subset,substitute,substr,substring,sum,summary,sunflowerplot,svd,%
      sweep,switch,symbol,symbols,symnum,sys,status,system,t,table,%
      tabulate,tan,tanh,tapply,tempfile,terms,terrain,tetragamma,text,%
      time,title,topo,trace,traceback,transform,tri,trigamma,trunc,try,%
      ts,tsp,typeof,unclass,undebug,undoc,union,unique,uniroot,unix,%
      unlink,unlist,unname,untrace,update,upper,url,UseMethod,var,%
      variable,vector,Version,vi,warning,warnings,weighted,weights,%
      which,while,window,write,\%x\%,x11,X11,xedit,xemacs,xinch,xor,%
      xpdrows,xy,xyinch,yinch,zapsmall,zip},%
   otherkeywords={!,!=,~,$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,_,/},%
   alsoother={._$},%
   sensitive,%
   morecomment=[l]\#,%
   morestring=[d]",%
   morestring=[d]'% 2001 Robert Denham
  }%

----

#comment

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