Rで回帰分析
引き続きデータマイニングの基礎の学習です。Rで、回帰分析を行います。
ファイルの読み込み
回帰分析以前に、まずは対象とするデータをCSVファイルから読み込みます。
Rはメニューからもワーキングディレクトリを設定できますがプログラム側からも指定ができます。
setwd("c:/work/R")
これで、ワーキングディレクトリを c:\work\R に設定できます。
ワーキングディレクトリに下記のようなCSVファイルをおいておきます。
month,degree,amount 1月,5.1,772 2月,6.7,948 3月,9.8,1251 4月,13.6,1211 5月,19,1287 6月,22.5,1653 7月,25.6,1559 8月,27.5,2389 9月,23.5,1189 10月,19.5,1155 11月,14.4,1271 12月,9.5,1045
このファイルを読み込むには、 read.csv を使います。
> data <- read.csv("2-1.csv") > data month degree amount 1 1月 5.1 772 2 2月 6.7 948 3 3月 9.8 1251 4 4月 13.6 1211 5 5月 19.0 1287 6 6月 22.5 1653 7 7月 25.6 1559 8 8月 27.5 2389 9 9月 23.5 1189 10 10月 19.5 1155 11 11月 14.4 1271 12 12月 9.5 1045
回帰分析の実行
まずは温度と量を分析したいので、この二つをモデル化します。表のラベルをもとに、二つのデータを取得します。モデルを作成するには「~(チルダ)」を使います。
> xymodel <- data$amount ~ data$degree
あとはこのモデルに対して、plotで散布図の描画、lmで回帰分析、ablineで回帰曲線を描画します。
> plot(xymodel) > result <- lm(xymodel) > abline(result)
回帰分析の結果は
> summary(result) Call: lm(formula = xymodel) Residuals: Min 1Q Median 3Q Max -424.70 -137.27 23.45 58.05 604.88 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 612.44 192.46 3.182 0.00978 ** data$degree 42.61 10.73 3.971 0.00264 ** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 270.7 on 10 degrees of freedom Multiple R-squared: 0.6119, Adjusted R-squared: 0.5731 F-statistic: 15.77 on 1 and 10 DF, p-value: 0.002639
この、Estimateの612.44 と 42.61が、回帰係数になります。
この回帰式は、 y = 42.61x + 612.44 と求められました。
試しに、5.1の時の値、 42.61*5.1 + 612.44 を求めると、829.751 となり、772との残差は60程度であることがわかります。
なお、このデータにおける相関は、
> cor(data$degree, data$amount) [1] 0.782259
cor関数で求めることができます。