備忘録的なやつです。
前回の続き。
【R】ROC曲線を書く
【R】ROC曲線を書く2
ggplot2(ggroc)を使ってROC曲線を描きます。
必要なパッケージ
使うパッケージはggplot2とpROCです。
library(ggplot2)
library(pROC)
データの読み込みと確認
pROCに入っているデータ(aSAH)を読み込んで、**summary()**関数で確認。
# データの読み込み
df <- aSAH
# データの確認
summary(df)
⬇実行結果
> #データの読み込み
> df <- aSAH
> #データの確認
> summary(df)
gos6 outcome gender age wfns s100b ndka
1:28 Good:72 Male :42 Min. :18.0 1:39 Min. :0.030 Min. : 3.01
2: 0 Poor:41 Female:71 1st Qu.:42.0 2:32 1st Qu.:0.090 1st Qu.: 9.01
3:13 Median :51.0 3: 4 Median :0.140 Median : 12.22
4: 6 Mean :51.1 4:16 Mean :0.247 Mean : 19.66
5:66 3rd Qu.:61.0 5:22 3rd Qu.:0.330 3rd Qu.: 17.30
Max. :81.0 Max. :2.070 Max. :419.19
roc()でROC曲線のオブジェクトを作成する
まず、**roc()**の結果をオブジェクトに格納しておきます。
roc(Y ~ X1 + X2 + ..., data, ci)
Y
:疾患の有無(2値変数)
X
:検査の変数
data
:データフレーム
ci
:信頼区間
今回はY
がoutocome、X
をs100b、ndka、wfnsとします。
ROC <- roc(outcome ~ s100b + ndka + wfns, data = df, ci = TRUE)
ROC
⬇実行結果
> ROC <- roc(outcome ~ s100b + ndka + wfns, data = df, ci = TRUE)
Setting levels: control = Good, case = Poor
Setting direction: controls < cases
Setting levels: control = Good, case = Poor
Setting direction: controls < cases
Setting levels: control = Good, case = Poor
Setting direction: controls < cases
> ROC
$s100b
Call:
roc.formula(formula = outcome ~ s100b, data = df, ci = TRUE)
Data: s100b in 72 controls (outcome Good) < 41 cases (outcome Poor).
Area under the curve: 0.7314
95% CI: 0.6301-0.8326 (DeLong)
$ndka
Call:
roc.formula(formula = outcome ~ ndka, data = df, ci = TRUE)
Data: ndka in 72 controls (outcome Good) < 41 cases (outcome Poor).
Area under the curve: 0.612
95% CI: 0.5012-0.7227 (DeLong)
$wfns
Call:
roc.formula(formula = outcome ~ wfns, data = df, ci = TRUE)
Data: wfns in 72 controls (outcome Good) < 41 cases (outcome Poor).
Area under the curve: 0.8237
95% CI: 0.7485-0.8988 (DeLong)
ggroc()でROC曲線を描画する
さきほど作成したROCオブジェクトを使って、**ggroc()**でROC曲線を描いてみます。
ggroc(ROC)
⬇実行結果
体裁を整えてみます。
ggroc(ROC,
aes = c("linetype", "color"), #線タイプ、色
size = 1, #サイズ
legacy.axes = TRUE) + # TRUE:x軸の目盛りを1-特異度に合わせて左が0、右が1となるように表示
geom_abline(color = "dark grey", size = 0.5) + # AUROC=0.5となるラインを描画
theme_classic()
⬇実行結果
最終的なスクリプト
# ROC曲線
# Rをきれいにする
rm(list = ls())
# ライブラリの読み込み
library(ggplot2)
library(pROC)
# データの読み込み
df <- aSAH
# データの確認
summary(df)
# roc()でROC曲線のオブジェクトを作成する
ROC <- roc(outcome ~ s100b + ndka + wfns, data = df, ci = TRUE)
ROC
# ggroc()でROC曲線を描画する
ggroc(ROC)
# ggroc()でROC曲線を描画する2
ggroc(ROC,
aes = c("linetype", "color"), #線タイプ、色
size = 1, #サイズ
legacy.axes = TRUE) + # TRUE:x軸の目盛りを1-特異度に合わせて左が0、右が1となるように表示
geom_abline(color = "dark grey", size = 0.5) + # AUROC=0.5となるラインを描画
theme_classic()