Skip to Content
R Programming Fundamentals
book

R Programming Fundamentals

by Kaelen Medeiros
September 2018
Beginner
206 pages
4h 27m
English
Packt Publishing
Content preview from R Programming Fundamentals

Creating an Ordered Factor Variable

Herein, we will create an ordered factor variable in a dataset. In order to do so, the following steps need to be executed:

  1. Create a vector called gas_price using the following code:

gas_price <- rep(c("low", "medium", "high"), times = 146)gas_price <- gas_price[-1]

It will indicate if gas prices in that area are low, medium, or high on average.

  1. Add the gas_price variable to the midwest dataset as follows:
midwest$gas_price <- factor(gas_price,                        levels = c("low", "medium", "high"),                        ordered = TRUE)
  1. Verify that the variable has been added to the dataset successfully using table() as follows:

table(midwest$gas_price)

Factor variables are a very important data type in R, since, as we learned previously, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R Programming Fundamentals

R Programming Fundamentals

Samik Sen, Marcin Dubel
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781789612998Supplemental Content