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           10989        13978        10475
## NNE          7937         9782         8002
## NE           8715         9335        10092
## ENE          9965         9592         9605
## E           11071        11237        10123
## ESE          9055         9536        10290
## SE          11331        11398        12919
## SSE         10946        10954        11089
## S           11043        10519        11788
## SSW         10809         9272         9902
## SW          10793        10135        11166
## WSW         11136         8392        11700
## W           12122        10183        12411
## WNW         10045         9067        10846
## NW           9705        10488        10315
## NNW          7954         9468         9358


Your donation will support ongoing development and give you access to the PDF version of this 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.