Y's note

Web技術・プロダクトマネジメント・そして経営について

本ブログの更新を停止しており、今後は下記Noteに記載していきます。
https://note.com/yutakikuchi/

CentOSでR言語を使ってみたことのまとめ

Rクックブック

Rクックブック

はじめに

統計的処理と結果のグラフ化をするために学生時代はmatlabを利用していました。matlabは行列演算に優れ使い易い言語だったのですが、一番の難点はMathWorks社の商用製品である事です。しかも高い。MathWorks 日本 - MATLAB / Simulinkによる数値計算 - マスワークス公式日本語サイト はてなブックマーク - MathWorks 日本 - MATLAB / Simulinkによる数値計算 - マスワークス公式日本語サイト matlabと同様の機能をもつ(互換性は無い)scilabというFreeの言語もありますが、イマイチ流行っている感はありません。Home - Scilab WebSite はてなブックマーク - Home - Scilab WebSite Freeの言語で統計処理をやるのはR言語が主流のようなので、それに習ってR言語を使って行きます。今日はR言語/RCommander周りの説明を行います。多少癖がある言語なので学習が面倒ですが慣れると優れものと聞くので頑張って勉強します。The R Project for Statistical Computing はてなブックマーク - The R Project for Statistical Computing

CentOSへのInstall

環境

CentOS5.7、64bit環境、Core2Duoです。

$ cat /etc/redhat-release 
CentOS release 5.7 (Final)

$ cat /proc/cpuinfo
cat /proc/cpuinfo 
processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 23
model name	: Intel(R) Core(TM)2 Duo CPU     E7600  @ 3.06GHz

$ uname -m
x86_64
install手順のまとめ

次の項目で失敗した内容も含めて手順を記載していますが、簡単にまとめると以下のパッケージが必要です。それぞれのパッケージが単純なyum reposに登録されていないので/etc/yum.repos.d/R.repoの登録とrpmforge経由でのinstallが必要になります。

  • R.x86_64 0:2.10.0-2.el5 (R.repoの登録)
  • perl-File-Copy-Recursive.noarch 0:0.38-1.el5.rf (rpmforge経由)
yum install手順

R.repoを作成してyumでinstallできるようにします。

$ sudo vim /etc/yum.repos.d/R.repo
[R-project]
name=R project for Statistical Computing repository
baseurl=http://rm.mirror.garr.it/mirrors/CRAN/bin/linux/redhat/el5/x86_64/
failovermethod=priority
enabled=1
gpgcheck=0
priority=15

yum installします。しかしperl(File::Copy::Recursive)が無いということでinstallができません。

$ sudo yum install R
R-project                                                                                            | 1.0 kB     00:00     
R-project/primary                                                                                    | 2.8 kB     00:00     
R-project                                                                                                               5/5
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package R.x86_64 0:2.10.0-2.el5 set to be updated
--> Processing Dependency: R-devel = 2.10.0-2.el5 for package: R
--> Processing Dependency: libRmath-devel = 2.10.0-2.el5 for package: R
--> Running transaction check
(略)
R-core-2.10.0-2.el5.x86_64 from R-project has depsolving problems
  --> Missing Dependency: perl(File::Copy::Recursive) is needed by package R-core-2.10.0-2.el5.x86_64 (R-project)
Error: Missing Dependency: perl(File::Copy::Recursive) is needed by package R-core-2.10.0-2.el5.x86_64 (R-project)

CPANでFile::Copy::Recursiveを探すとあるのでcpan経由でinstallします。install後にcpanコマンドでinstallされているかを確認します。File::Copy::Recursive - search.cpan.org はてなブックマーク - File::Copy::Recursive - search.cpan.org

$ sudo cpan
cpan> install File::Copy::Recursive
CPAN: Storable loaded ok
Going to read /home/yuta/.cpan/Metadata
  Database was generated on Mon, 02 Jul 2012 03:58:03 GMT
Running install for module File::Copy::Recursive
Running make for D/DM/DMUEY/File-Copy-Recursive-0.38.tar.gz
CPAN: Digest::MD5 loaded ok
CPAN: Compress::Zlib loaded ok
(略)
Installing /usr/lib/perl5/site_perl/5.8.8/File/Copy/Recursive.pm
Installing /usr/share/man/man3/File::Copy::Recursive.3pm
Writing /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/File/Copy/Recursive/.packlist
Appending installation info to /usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/perllocal.pod
  /usr/bin/make install  -- OK
cpan> quit

$ cpan -a | grep -i Recursive
File::Copy::Recursive          0.38      0.38  D/DM/DMUEY/File-Copy-Recursive-0.38.tar.gz

再度yum installに挑戦しましたが、また同じエラーが出ます。

$ sudo yum install R -y
R-core-2.10.0-2.el5.x86_64 from R-project has depsolving problems
  --> Missing Dependency: perl(File::Copy::Recursive) is needed by package R-core-2.10.0-2.el5.x86_64 (R-project)
Error: Missing Dependency: perl(File::Copy::Recursive) is needed by package R-core-2.10.0-2.el5.x86_64 (R-project)
 You could try using --skip-broken to work around the problem
 You could try running: package-cleanup --problems
                        package-cleanup --dupes
                        rpm -Va --nofiles --nodigest

File::Copy::Recursiveをrmpforge経由でinstallすることを試みます。まずはyum-prioritiesをinstallします。さらにCentOS-Base.repoの各項目にpriority=1を追記します。

$ sudo yum install yum-priorities -y
yum-priorities-1.1.16-21.el5.centos.noarch.rpm                                                       |  16 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : yum-priorities                                                                                       1/1 

Installed:
  yum-priorities.noarch 0:1.1.16-21.el5.centos                                                                              

Complete!

$ sudo vi /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5
priority=1  #<== 追記

(略)

rpmforge-release-0.5.2-2.el5.rf.x86_64.rpmを取得してinstallします。さらにrpmforge.repoのpriority=10を追記します。

$ wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm

$ sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
警告: rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm: ヘッダ V3 DSA signature: NOKEY, key ID 6b8d79e6
準備中...                ########################################### [100%]
   1:rpmforge-release       ########################################### [100%]

$ sudo vim /etc/yum.repos.d/rpmforge.repo
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag 
baseurl = http://apt.sw.be/redhat/el5/en/$basearch/rpmforge
mirrorlist = http://apt.sw.be/redhat/el5/en/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1 
protect = 0 
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1 
priority = 10

sudo yum install perl-File-Copy-Recursiveをします。

$ sudo yum install perl-File-Copy-Recursive -y
(略)
Downloading Packages:
perl-File-Copy-Recursive-0.38-1.el5.rf.noarch.rpm                                                    |  22 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : perl-File-Copy-Recursive                                                                             1/1 

Installed:
  perl-File-Copy-Recursive.noarch 0:0.38-1.el5.rf                                                                           

Complete!

再度yum install Rに挑戦します。今度はうまく行きます。

$ sudo yum install R -y
(略)
Installed:
  R.x86_64 0:2.10.0-2.el5                                                                                                   

Dependency Installed:
  R-core.x86_64 0:2.10.0-2.el5             R-devel.x86_64 0:2.10.0-2.el5              bzip2-devel.x86_64 0:1.0.3-6.el5_5    
  dialog.x86_64 0:1.0.20051107-1.2.2       gcc-gfortran.x86_64 0:4.1.2-52.el5_8.1     libRmath.x86_64 0:2.10.0-2.el5        
  libRmath-devel.x86_64 0:2.10.0-2.el5     libgfortran.x86_64 0:4.1.2-52.el5_8.1      pcre-devel.x86_64 0:6.6-6.el5_6.1     
  tetex.x86_64 0:3.0-33.13.el5             tetex-dvips.x86_64 0:3.0-33.13.el5         tetex-fonts.x86_64 0:3.0-33.13.el5    
  tetex-latex.x86_64 0:3.0-33.13.el5       xdg-utils.noarch 0:1.0.2-2.el5.centos     

Dependency Updated:
  cpp.x86_64 0:4.1.2-52.el5_8.1          gcc.x86_64 0:4.1.2-52.el5_8.1                gcc-c++.x86_64 0:4.1.2-52.el5_8.1   
  libgcc.i386 0:4.1.2-52.el5_8.1         libgcc.x86_64 0:4.1.2-52.el5_8.1             libstdc++.i386 0:4.1.2-52.el5_8.1   
  libstdc++.x86_64 0:4.1.2-52.el5_8.1    libstdc++-devel.x86_64 0:4.1.2-52.el5_8.1   

Complete!

R言語を起動してみます。問題なく起動します。とりあえずinstallはこれにて終了です。

$ R

R version 2.10.0 (2009-10-26)
Copyright (C) 2009 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

Rは、自由なソフトウェアであり、「完全に無保証」です。 
一定の条件に従えば、自由にこれを再配布することができます。 
配布条件の詳細に関しては、'license()'あるいは'licence()'と入力してください。 

Rは多くの貢献者による共同プロジェクトです。 
詳しくは'contributors()'と入力してください。 
また、RやRのパッケージを出版物で引用する際の形式については
'citation()'と入力してください。 

'demo()'と入力すればデモをみることができます。 
'help()'とすればオンラインヘルプが出ます。 
'help.start()'でHTMLブラウザによるヘルプがみられます。 
'q()'と入力すればRを終了します。 

> 

簡単に触ってみる

Demoを実行

R起動後に「'demo()'と入力すればデモをみることができます。 」という説明文が表示されるのでdemo()を見てみます。demo()と入力すると表示可能なもの一覧が取得できるので、その中からgraphicsというものを見てみます。Rを起動後にdemo(graphics)と実行します。コンソールにplotの式とGUIには画像が出力されると思います。


利用できるライブラリを確認

/usr/lib64/R/library以下にある使用可能なライブラリ一覧を表示します。R言語コマンドラインlibrary()と実行します。

> library()


  ライブラリ (パッケージ '/usr/lib64/R/library' 中): 

KernSmooth              Functions for kernel smoothing for Wand & Jones
                        (1995)
MASS                    Main Package of Venables and Ripley's MASS
Matrix                  Sparse and Dense Matrix Classes and Methods
base                    The R Base Package
boot                    Bootstrap R (S-Plus) Functions (Canty)
class                   Functions for Classification
cluster                 Cluster Analysis Extended Rousseeuw et al.
codetools               Code Analysis Tools for R
datasets                The R Datasets Package
foreign                 Read Data Stored by Minitab, S, SAS, SPSS,
                        Stata, Systat, dBase, ...
grDevices               The R Graphics Devices and Support for Colours
                        and Fonts
graphics                The R Graphics Package
grid                    The Grid Graphics Package
lattice                 Lattice Graphics
methods                 Formal Methods and Classes
mgcv                    GAMs with GCV/AIC/REML smoothness estimation
                        and GAMMs by PQL
nlme                    Linear and Nonlinear Mixed Effects Models
nnet                    Feed-forward Neural Networks and Multinomial
                        Log-Linear Models
rpart                   Recursive Partitioning
spatial                 Functions for Kriging and Point Pattern
                        Analysis
splines                 Regression Spline Functions and Classes
stats                   The R Stats Package
stats4                  Statistical Functions using S4 Classes
survival                Survival analysis, including penalised
                        likelihood.
tcltk                   Tcl/Tk Interface
tools                   Tools for Package Development
utils                   The R Utils Package
とりえあずはPlot

2次元データのplotをしてみます。sin関数を利用した波形です。plot(sin,-pi,2*pi)という一行でplotできます。

> plot(sin, -pi, 2*pi)


外部ソースファイルの読み込み

R言語コマンドラインで毎回命令文を実行すると面倒です。そんな時は外部ファイルに落とし込んでRのコマンドラインからsource()で読み込みます。ここではplot(cos,-pi,2*pi)という一行をcos.Rというファイルに保存してRから読み込ませます。

$ vi /home/yuta/work/dev/R/cos.R
plot(cos,-pi,2*pi) #記述

$ R
> source("/home/yuta/work/dev/R/cos.R")


install.packages()

perlCPANのようにRにはCRANというネットワークがあります。様々なRユーザが便利なプログラムを開発し、配布可能なパッケージングにしてCRANからダウンロードできます。CRANのパッケージをinstallして使えるようにするにはinstall.packages()を実行します。ここではrglという3次元plotのパッケージをinstallします。rglをinstallしようとするとコンパイルエラーになります。GL/glu.hというincludeファイルが見当たらないようです。glu.hはfreeglut-develに含まれているので先にsudo yum install freeglut-devel -yをすると良いと思います。freeglut-develをinstallした後にサイドinstall.package("rgl")を行うと問題なくコンパイルが通り、library(rgl)で読み込みが可能になります。search()というコマンドで読み込みが完了しているパッケージ一覧にもrglが載ります。library(rgl)を読み込んだ後にopen3d()とexample(rgl.surface)の実行により3dグラフが表示されます。install.packages()を利用する際はsudo Rで起動すると良いと思います。

> install.packages("rgl")
* installing *source* package ‘rgl’ ...
checking for gcc... gcc -m64 -std=gnu99
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc -m64 -std=gnu99 accepts -g... yes
checking for gcc -m64 -std=gnu99 option to accept ISO C89... none needed
checking how to run the C preprocessor... gcc -m64 -std=gnu99 -E
checking for gcc... (cached) gcc -m64 -std=gnu99
checking whether we are using the GNU C compiler... (cached) yes
checking whether gcc -m64 -std=gnu99 accepts -g... (cached) yes
checking for gcc -m64 -std=gnu99 option to accept ISO C89... (cached) none needed
checking for libpng-config... yes
configure: using libpng-config
configure: using libpng dynamic linkage
checking for X... libraries , headers 
checking GL/gl.h usability... yes
checking GL/gl.h presence... yes
checking for GL/gl.h... yes
checking GL/glu.h usability... no
checking GL/glu.h presence... no
checking for GL/glu.h... no
configure: error: missing required header GL/glu.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/usr/lib64/R/library/rgl’

> quit()

$ sudo yum install freeglut-devel -y
Running Transaction
  Installing     : mesa-libGLU-devel                                                                               1/3 
  Installing     : freeglut-devel                                                                                       2/3 
  Installing     : freeglut-devel                                                                                       3/3 

Installed:
  freeglut-devel.i386 0:2.4.0-7.1.el5                         freeglut-devel.x86_64 0:2.4.0-7.1.el5                        

Dependency Installed:
  mesa-libGLU-devel.x86_64 0:6.5.1-7.10.el5                                                                                 

Complete!

$ sudo R

> install.packages("rgl")
 install.packages("rgl") 中で警告がありました: 
  引数 'lib' が欠けています:/usr/lib64/R/library を使います  
 URL 'http://cran.md.tsukuba.ac.jp/src/contrib/rgl_0.92.880.tar.gz' を試しています 
Content type 'application/x-gzip' length 1742168 bytes (1.7 Mb)
 開かれた URL 
==================================================
downloaded 1.7 Mb

* installing *source* package ‘rgl’ ...
checking for gcc... gcc -m64 -std=gnu99
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc -m64 -std=gnu99 accepts -g... yes
checking for gcc -m64 -std=gnu99 option to accept ISO C89... none needed
checking how to run the C preprocessor... gcc -m64 -std=gnu99 -E
checking for gcc... (cached) gcc -m64 -std=gnu99
checking whether we are using the GNU C compiler... (cached) yes
checking whether gcc -m64 -std=gnu99 accepts -g... (cached) yes
checking for gcc -m64 -std=gnu99 option to accept ISO C89... (cached) none needed
checking for libpng-config... yes
configure: using libpng-config
configure: using libpng dynamic linkage
checking for X... libraries , headers 
checking GL/gl.h usability... yes
checking GL/gl.h presence... yes
checking for GL/gl.h... yes
checking GL/glu.h usability... yes
checking GL/glu.h presence... yes
checking for GL/glu.h... yes
checking for glEnd in -lGL... yes
checking for gluProject in -lGLU... yes
checking for freetype-config... yes
configure: using Freetype and FTGL
configure: creating ./config.status
config.status: creating src/Makevars

(略)

** R
** demo
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices ...
* DONE (rgl)

 ダウンロードされたパッケージは、以下にあります 
 	‘/tmp/RtmpvsHjUt/downloaded_packages’ 
 '.Library' 中のパッケージの HTML 索引を更新します

> library(rgl) 
> search()  
[1] ".GlobalEnv"        "package:rgl"       "package:stats"      
[4] "package:graphics"  "package:grDevices" "package:utils"      
[7] "package:datasets"  "package:methods"   "Autoloads"         
[10] "package:base"

> open3d()
[1] 1
> example(rgl.surface)

RCommander

install

Rを総合的な実行環境ツールとしてRCommanderというものがあります。これもCRANでpackageが配布されているのでinstall.packagesで入れます。CentOSで試してみたところCRANのmirrorサーバからなぜかパッケージが取得できなかったので(package ‘Rcmdr’ is not availableというエラーが表示されてしまう)、直接tar.gzファイルを落としてきてlocalのディレクトリからinstall.packagesを試みます。localのディレクトリからinstall.packagesを使うには落としてきたtar.gzを第一引数に指定し、destdir、reposというオプションをそれぞれ指定します。ここではdestdirはRを立ち上げたカレントディレクトリ、reposはNULLを指定しています。最新のRCommanderはVersionが1.8-4ですが、RのVersionを2.14以上を求められるので自分の環境に合わせて1.6-1を取得しています。RのVersionはsessioninfo()というコマンドで分かります。私の環境はR version 2.10.0 (2009-10-26)でした。またRCommanderのVersionに合わせたcarも取得しています。install後にLibrary(Rcmdr)と入力すると必要なパッケージを更に追加でinstallして、その後に起動します。

$ sudo R
> install.packages("Rcmdr")
 install.packages("Rcmdr") 中で警告がありました: 
  引数 'lib' が欠けています:/usr/lib64/R/library を使います  
 警告メッセージ: 
In getDependencies(pkgs, dependencies, available, lib) :
  package ‘Rcmdr’ is not available

> sessionInfo()
R version 2.10.0 (2009-10-26) 
x86_64-redhat-linux-gnu

> quit()

$ wget http://essrc.hyogo-u.ac.jp/cran/src/contrib/Archive/Rcmdr/Rcmdr_1.6-1.tar.gz
$ wget http://essrc.hyogo-u.ac.jp/cran/src/contrib/Archive/car/car_2.0-0.tar.gz
$ sudo R

> install.packages("leaps")
> install.packages( "car_2.0-0.tar.gz", destdir=".", repos=NULL )
> install.packages( "Rcmdr_1.6-1.tar.gz", destdir=".", repos=NULL )
> Library(Rcmdr)
実行

上と同じくcosのグラフをplotすることをしてみます。操作はとても簡単でスクリプトウィンドという箇所にplot文を入力するだけです。入力後に右にある実行というボタンを押下します。そうすると上で表示されたcosグラフが表示されます。

初心者向けR言語資料

slideshareR言語について初心者向けの解説をしている内容を二つほど見つけました。今後はこれらの内容について学習を進めて行きたいと思います。