How to create an ordinal variable in R?



An ordinal variable is a type of categorical variable which has natural ordering. For example, an ordinal variable could be level of salary something defined with Low, Medium, and High categories here we have three categories but there exists a natural order in these categories as low salary is always less than the medium, medium is always less than high. To create an ordinal variable in R, we can use the order argument along with factor function while creating the variable. Follow the below steps to create an ordinal variable in R −

  • Create a categorical column with factor function where order argument is set to TRUE
  • Look at the structure of the data frame

Creating a data frame df with ordinal variable x

Let's create a data frame as shown below −

 Live Demo

x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x
1 Medium
2 Medium
3 Low
4 Medium
5 Low
6 Medium
7 High
8 Low
9 Medium
10 High
11 Medium
12 High
13 Medium
14 Medium
15 Low
16 Low
17 Low
18 Medium
19 Low
20 Medium

Checking the structure of data frame df

Use str function to check the structure of data frame df −

 Live Demo

x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
str(df)

Output

'data.frame': 20 obs. of 1 variable:
$ x: Ord.factor w/ 3 levels "Low"<"Medium"<..: 2 2 1 2 1 2 3 1 2 3 ...

Here we can see that x is an ordered factor which means it is an ordinal variable.


Advertisements