2
2

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 で変数(オブジェクト)の保存と呼び出し

Posted at

はじめに

Rで開発を行っていると、途中までの実行結果を保存し後で呼び出ししたくなることがあった。その方法を備忘録として残しておく。

分析の例

データセットは「Rでの性別、身長、体重、血液型データの作成方法」で作成したものを「R shiny でデータの基礎分析用アプリの作成①」で csv に保存したので、それを用いて行う。

まずデータセットの読み込みと中身の確認を行う。

df <- read.csv("./data.csv")
str(df)
出力
'data.frame':	1000 obs. of  5 variables:
 $ X     : int  1 2 3 4 5 6 7 8 9 10 ...
 $ SEX   : chr  "female" "male" "male" "male" ...
 $ HEIGHT: num  154 178 163 176 156 ...
 $ WEIGHT: num  48 70.8 48.2 76.4 40.9 ...
 $ BLOOD : chr  "O" "A" "A" "O" ...

これから身長から体重を予測する線形回帰モデルを作成する。

result <- lm(WEIGHT~HEIGHT,data=df)
summary(result)
出力
Call:
lm(formula = WEIGHT ~ HEIGHT, data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-35.495  -7.378  -0.236   7.196  40.649 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -85.32669    6.35537  -13.43   <2e-16 ***
HEIGHT        0.87842    0.03846   22.84   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 11.21 on 998 degrees of freedom
Multiple R-squared:  0.3433,	Adjusted R-squared:  0.3426 
F-statistic: 521.7 on 1 and 998 DF,  p-value: < 2.2e-16

この結果を保存する場合を考える。

変数(オブジェクト)を保存する場合

saveRDS関数を使って変数を保存する。

saveRDS(result, file = "./result.obj")

これで result.obj に変数の状態を保存できた。

保存した変数(オブジェクト)を呼び出す場合

呼び出すのも簡単で、readRDS関数を用いる。

result_new <- readRDS("./result.obj")
summary(result_new)
出力
Call:
lm(formula = WEIGHT ~ HEIGHT, data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-35.495  -7.378  -0.236   7.196  40.649 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -85.32669    6.35537  -13.43   <2e-16 ***
HEIGHT        0.87842    0.03846   22.84   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 11.21 on 998 degrees of freedom
Multiple R-squared:  0.3433,	Adjusted R-squared:  0.3426 
F-statistic: 521.7 on 1 and 998 DF,  p-value: < 2.2e-16

オブジェクトごと読みだせているのが分かる。

おわりに

分析の結果を保存して途中で他の作業を行うことがあるので、saveRDS,readRDSは覚えておきたい関数の一つであった。今後も簡単な tips でも、何かあれば記事にしていきたいと思う。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?