November 13, 2019

R Markdown

Chapter 15

Factors are used to work with categorical variables, variables that have a fixed and known set of possible values.

Factor Examples

x1 <- c("Dec", "Apr", "Jan", "Mar")
x1
## [1] "Dec" "Apr" "Jan" "Mar"
class(x1)
## [1] "character"
sort(x1)
## [1] "Apr" "Dec" "Jan" "Mar"

Factor Examples

month_levels <- c(
  "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
)

y1 <- factor(x1, levels = month_levels)
y1
## [1] Dec Apr Jan Mar
## Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
sort(y1)
## [1] Jan Mar Apr Dec
## Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Factor Examples

x2 <- c("Dec", "Apr", "Jam", "Mar")

y2 <- factor(x2, levels = month_levels)
y2
## [1] Dec  Apr  <NA> Mar 
## Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
y2 <- parse_factor(x2, levels = month_levels)
## Warning: 1 parsing failure.
## row col           expected actual
##   3  -- value in level set    Jam

Factor Examples

factor(x1)
## [1] Dec Apr Jan Mar
## Levels: Apr Dec Jan Mar
f1 <- factor(x1, levels = unique(x1))
f1
## [1] Dec Apr Jan Mar
## Levels: Dec Apr Jan Mar
f2 <- x1 %>% factor() %>% fct_inorder()
f2
## [1] Dec Apr Jan Mar
## Levels: Dec Apr Jan Mar