How to Access Slots in S4 Classes in R: Area Under Curve Example
In the R statistical package, you have various ways of representing and packaging data. The most simple is in a single variable. More complex representations include vectors, lists, matrices, and data frames. An even more complex representation is S4 Classes, which are intended to simulate object-oriented programming in R.
I was using an R package that returned an S4 class, but I wasn’t sure how to access the properties of the class. A $ sign didn’t work, like it does for lists and data frames. After some searching, I found out that the @ sign is used for this.
More specifically, I am using the ROCR package and wanted to get the area under the curve. Below is how I did that for some randomly generated data.
require(ROCR, quietly=T)
auc = function(numericPredictions, actualClasses)
{
pred = prediction(numericPredictions, actualClasses)
perf = performance(pred, 'auc')
return(perf@y.values[[1]][1])
}
actualClasses = c(rep("a", 500), rep("b", 500))
numericPredictions = rbinom(length(actualClasses), 1, 0.5)
print(auc(numericPredictions, actualClasses))
For S4 classes you can use ” @ ” to get access to the slots.