- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 −
x<- factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo w","Medium","High")) df<-data.frame(x) str(df)
'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.
- How to create a dummy variable in R?
- How to replace numbers with ordinal strings for a survey in an R vector?
- How to create a scatterplot between a variable and an equation in R?
- How to create a frequency column for categorical variable in an R data frame?
- How to create a lagged variable in R for groups?
- How to create a point chart for categorical variable in R?
- How to create a column with binary variable based on a condition of other variable in an R data frame?
- Create stacked bar plot for one categorical variable in an R dataframe.
- How to change ordinal X-axis label to text labels using ggplot2 in R?
- How to create a scatterplot with log10 of dependent variable in R?
- How to create a binary random variable in R with given probability?
- How to create an empty matrix in R?
- How to create an exponential curve in R?
- How to create an arrow in base R?
- How to create an S4 object in R?