Tokyo.R@36

~knitrパッケージではじめる~『R MarkdownでReproducible Research』の基礎編のコード

基礎の基礎

やぁ、みんなこんにちは! ぼくのRのversionは

R.version.string
## [1] "R version 3.0.1 (2013-05-16)"

ダヨ!!!

インラインチャンク

carsデータに関する回帰分析だーっ!

x <- lm(dist ~ speed, data = cars)

この結果、回帰係数の切片は3.9324となった。

数式の表示

数式も表示できるヨ!! $でインラインな数式\( f(x) = ax^2 + bx + c \)、$$で1行まるごと数式 \[ f(x) = ax^2 + bx + c \]

表(テーブル)の作成

表の作成も可能

x <- lm(dist ~ speed, data = cars)
kable(summary(x)$coef, format = "html", digits = 2)
Estimate Std. Error t value Pr(>|t|)
(Intercept) -17.58 6.76 -2.60 0.01
speed 3.93 0.42 9.46 0.00

図の作成

図は普通にPLOT系の関数を使えばOK。 fig.width/heightは"出力される画像"のサイズを指定する(単位:インチ)。

plot(cars)

plot of chunk plot_cars

ggplot2や他のパッケージもOK

library(ggplot2)
qplot(Sepal.Length, Sepal.Width, data = iris, colour = Species)

plot of chunk plot_iris

グローバルなオプション設定

# opts_chunk$setで指定したものは、 全体に設定されるので以降指定しなくてOK
opts_chunk$set(fig.width = 6, fig.height = 6)

一応のセッションインフォ

sessionInfo()
## R version 3.0.1 (2013-05-16)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## 
## locale:
## [1] LC_COLLATE=Japanese_Japan.932  LC_CTYPE=Japanese_Japan.932   
## [3] LC_MONETARY=Japanese_Japan.932 LC_NUMERIC=C                  
## [5] LC_TIME=Japanese_Japan.932    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_0.9.3.1 knitr_1.5      
## 
## loaded via a namespace (and not attached):
##  [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4      
##  [4] evaluate_0.5.1     formatR_0.10       grid_3.0.1        
##  [7] gtable_0.1.2       labeling_0.2       MASS_7.3-29       
## [10] munsell_0.4.2      plyr_1.8           proto_0.3-10      
## [13] RColorBrewer_1.0-5 reshape2_1.2.2     scales_0.2.3      
## [16] stringr_0.6.2      tools_3.0.1