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 Factor Variables in a Dataset

Herein, we will create factor variables in a dataset both one at a time and by using a method that converts multiple variables at once. In order to do so, the following steps have to be executed:

  1. Load the datasets library:

library(datasets)
  1. Load the midwest dataset and examine it with str():

data(midwest) str(midwest)
  1. Convert the state variable to a factor by using as.factor():

midwest$state <- as.factor(midwest$state)
  1. Load the band_instruments dataset and examine it with str():

data(band_instruments)str(band_instruments)
  1. Transform both variables in band_instruments to factor variables using apply():

band_instruments <- data.frame(apply(band_instruments, 2, as.factor))
  1. Double-check ...
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