1
$\begingroup$

To illustrate I use the segmentationOriginal dataset from the AppliedPredictiveModeling package:

> library(AppliedPredictiveModeling)
> data(segmentationOriginal)
> levels(factor(segmentationOriginal$Case))
[1] "Test"  "Train"

The authors of the data set have the training and testing data intermixed in the data set, so I wanted to separate the two types of data into separate data frames:

> training <- segmentationOriginal[segmentationOriginal$Case=="Train", ]
> testing <- segmentationOriginal[segmentationOriginal$Case=="Test", ]

However, the Case variable of the training data set still has two factor levels:

> str(training$Case)
 Factor w/ 2 levels "Test","Train": 2 2 2 2 2 2 2 2 2 2 ...

even if there is not a single Test factor in the Case variable any longer of the training set:

> which(training$Case == "Test")
integer(0)

Why is that or what is going on?

$\endgroup$

1 Answer 1

1
$\begingroup$

The elements of your Case factor can be one of two values ("levels"). An R's factor's levels defines the possible values, not just the current values. You may be misled by the default action for the factor function which creates levels corresponding to the values that exist in what you pass to it, but this is a one-time convenience and the factor levels are fixed at that time.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.