Raghav Sharma
Raghav Sharma

Reputation: 49

Data type double not converting to factor

Hi I am trying to convert my column within the data frame from "double" to a "factor", but its not working

I am trying to convert the "double" data type to "factor" but its converting it to an integer. I have tried a couple of other things from stackoverflow but nothing seems to work. I have provided my code below along with console output.

Task 1.5 - Change class type from Integer to Factor

typeof(iLPdf$class)  #check type
iLPdf$class <- as.factor(iLPdf$class)
typeof(iLPdf$class)  #check type


[1] "double"
iLPdf$class <- as.factor(iLPdf$class)
typeof(iLPdf$class)  #check type
[1] "integer"

Upvotes: 2

Views: 1248

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

The issue here is that typeof checks the internal representation of an object. Factors are represented as integers. To check that something is actually a factor, use is.factor instead. From the docs:

typeof determines the (R internal) type or storage mode of any object

To verify this "claim", you can check the well known iris Species' column which is a factor. typeof(iris$Species) will however return integer because to R factors are integers.

Using is.factor is a better option, this ultimately boils down to the difference between types and classes in R.

is.factor(iris$Species)
[1] TRUE

Upvotes: 2

Related Questions