Convert column to categorical in R

In R, as.factor is used to convert a column to a categorical variable (). Let’s look at an example of how to convert column type to categorical in R.

Let’s start by making the data frame.

Principal Component Analysis in R » finnstats

df<-data.frame(Product = c('A','B', 'C','D','E'),Price=c(612,447,45,374,831),Rank=c(1,2,0,1,0))
df

as a result, the data frame will be

  Product Price Rank
1       A   612    1
2       B   447    2
3       C    45    0
4       D   374    1
5       E   831    0

Now we can see the structure of the data frame.

LSTM Network in R » Recurrent Neural network » finnstats

str(df)
'data.frame':      5 obs. of  3 variables:
 $ Product: chr  "A" "B" "C" "D" ...
 $ Price  : num  612 447 45 374 831
 $ Rank   : num  1 2 0 1 0

Now it’s clear the Rank column is numeric. Let’s convert the same into categorical.

Let’s use as.factor to change the Rank column to categorical ()

df$Rank<-as.factor(df$Rank)
str(df)

Now the output become

Naive Bayes Classifier in Machine Learning » Prediction Model » finnstats

'data.frame':      5 obs. of  3 variables:
 $ Product: chr  "A" "B" "C" "D" ...
 $ Price  : num  612 447 45 374 831
 $ Rank   : Factor w/ 3 levels "0","1","2": 2 3 1 2 1

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *