10.36 Ordered Factor

20180723 Given our knowledge that compass directions have an obvious order, we convert the direction variables into an ordered factor. We do so using ordered=TRUE with base::factor().

# Note the names of the wind direction variables.

ds %>% 
  select(contains("_dir")) %>% 
  names() %T>%
  print() ->
vnames
## [1] "wind_gust_dir" "wind_dir_9am"  "wind_dir_3pm"
# Convert these variables from character to factor.

ds[vnames] %<>% 
  lapply(factor, levels=compass, ordered=TRUE) %>% 
  data.frame() %>% 
  as_tibble()
# Confirm they are now factors.

ds[vnames] %>% sapply(class)
##      wind_gust_dir wind_dir_9am wind_dir_3pm
## [1,] "ordered"     "ordered"    "ordered"   
## [2,] "factor"      "factor"     "factor"

We can again obtain a distribution of the variables to confirm that all we have changed is the data type.

# Verify the distribution has not changed.

ds %>%
  select(contains("_dir")) %>%
  sapply(table)
##     wind_gust_dir wind_dir_9am wind_dir_3pm
## N           11908        15053        11362
## NNE          8710        10723         8806
## NE           9434        10058        10950
## ENE         10730        10359        10357
## E           12007        12159        10906
## ESE          9850        10392        11179
## SE          12240        12320        13903
## SSE         11840        11924        11979
## S           11937        11313        12711
## SSW         11739        10072        10732
## SW          11604        10985        12005
## WSW         11970         9040        12571
## W           13030        10934        13283
## WNW         10786         9826        11675
## NW          10516        11309        11097
## NNW          8653        10226        10186


Your donation will support ongoing development and give you access to the PDF version of the book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.