# How to Calculate AUC (Area Under Curve) in R?

• Last Updated : 01 Apr, 2022

In this article, we will discuss how to calculate the AUC (Area under Curve) of the ROC (Receiver Operating Characteristic) curve in the R Programming Language.

The ROC (Receiver Operating Characteristic) curve helps us to visualize the true positive rate or true negative rate of a prediction based on some model. This helps us to assess how well a regression model has fitted the data. The AUC (Area under Curve) of this ROC curve helps us to determine the specificity and sensitivity of the model. The closer the AUC value is to the 1, the better the given model fits the data.

To create the ROC (Receiver Operating Characteristic) curve object in the R Language, we use the roc() function of the pROC package library. The pROC is an R Language package to display and analyze ROC curves. The roc() function takes the actual and predicted value as an argument and returns a ROC curve object as result. Then, to find the AUC (Area under Curve) of that curve, we use the auc() function. The auc() function takes the roc object as an argument and returns the area under the curve of that roc curve.

Syntax:

roc_object <- roc( response, prediction )

Parameters:

• response: determines the vector that contains the actual data.
• prediction: determines the vector that contains the data predicted by our model.

Example 1:

The area under the ROC curve of a logistic regression model.

## R

 `# load library pCOR ` `library``(pROC)`   `# sample data frame` `df_train <- ``data.frame``( x= ``c``(1,2,3,4,5),` `                  ``y= ``c``(1,5,8,15,26),` `                  ``z=``c``(0,1,1,0,0))` `df_test <- ``data.frame``( x= ``c``(6,7,8),` `                  ``y= ``c``(38,45,72),` `                  ``z=``c``(0,1,0))` `  `  `# fit logistic model` `model <- ``glm``(z ~ x+y, data=df_train)`   `# predicted data` `prediction <- ``predict``(model, df_test, type=``"response"``)`   `# create roc curve` `roc_object <- ``roc``( df_test\$z, prediction)`   `# calculate area under curve` `auc``( roc_object )`

Output:

```Setting levels: control = 0, case = 1
Setting direction: controls < cases
Area under the curve: 0.5```

Example 2:

The area under the ROC curve of a rev sequence model.

## R

 `# load library pROC` `library``(pROC)`   `# create sample_data` `var1 <- ``c``(1, 1, 1, 1, 0, 1, 1, 0, 1, 0,` `          ``1, 0, 1, 0, 0, 1, 0, 0, 0, 0)`   `# create prediction using seq_along()` `prediction <- ``rev``(``seq_along``(var1))`   `# print area under curve` `auc``( var1, prediction)`

Output:

```Setting levels: control = 0, case = 1
Setting direction: controls < cases
Area under the curve: 0.83```

My Personal Notes arrow_drop_up
Recommended Articles
Page :