0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

R tips 従属・独立変数に変数を指定したい場合

Posted at

はじめに

Rでの回帰分析などの関数(lm)を使う場合、従属変数、独立変数をチルダで指定する。この指定はベクトルで行われるが、for文で連続して回帰分析を行いたい場合、変数の指定方法がややこしい。その方法を備忘録として残しておく。

データは「RでReal estate valuationの基礎分析」で扱った、Real estate valuationデータセットを用いた。

エラーが出るコード

コード
library(openxlsx)
df <- read.xlsx("./Real_estate_valuation_data_set.xlsx")

coln <- colnames(df) #列名を保存しておく
colnames(df) <- c("No","X1","X2","X3","X4","X5","X6","Y") #新しい名前を付けておく
col_x <- c("X1","X2","X3","X4","X5","X6") #独立変数


for (x in col_x) {
  res <- lm(Y~x, df)
}

独立変数にX1, X2, ..., X6 を代入したいのだが、~でしているのはベクトルのため、エラーがでる。

出力
Error in model.frame.default(formula = Y ~ x, data = df, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'x')

これを回避するため eval 関数を使う。

eval 関数を用いたコード

上記の for 文部分を以下に書き換える。

コード
for (x in col_x) {
  eval(parse(text=paste0("res_", x," <- lm(Y~", x, ", df)")))
}

summary(res_X3)
出力
Call:
lm(formula = Y ~ X3, data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-35.396  -6.007  -1.195   4.831  73.483 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 45.8514271  0.6526105   70.26   <2e-16 ***
X3          -0.0072621  0.0003925  -18.50   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 10.07 on 412 degrees of freedom
Multiple R-squared:  0.4538,	Adjusted R-squared:  0.4524 
F-statistic: 342.2 on 1 and 412 DF,  p-value: < 2.2e-16

ちゃんとX3を独立変数として指定した場合の回帰分析結果が出力された。

おわりに

今回はeval関数を用いた方法を紹介したが、もっとスマートな方法を知っている方がいましたら、是非コメント下さい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?