10.51 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           16541        21256        16216
## NNE         12612        15373        12754
## NE          13743        14276        15672
## ENE         15575        14991        14845
## E           17553        17767        15694
## ESE         14533        15250        16360
## SE          17929        17753        19749
## SSE         16995        17509        17123
## S           17588        16357        18466
## SSW         17296        14577        16147
## SW          16601        15771        16969
....


If you find this curated material useful then you can consider a donation to support it's ongoing availability and give you access to the PDF version of this book. The material has been scoped up by Generative AI without permission or any kind of recompense so do consider a donation if you can afford it. Unlike Generative AI your access to this materials is freely given. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Togaware has a 30 year tradition of making popular open source software which includes sold privacy preserving productivity apps, rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0