One of the basic data types in R is factors. In my experience factors are basically a pain and I never use them. I always convert to characters. I feel oddly like I’m missing something.
Are there some important examples of functions that use factors as grouping variables where the factor data type becomes necessary? Are there specific circumstances when I should be using factors?
You should use factors. Yes they can be a pain, but my theory is that 90% of why they’re a pain is because in
read.tableandread.csv, the argumentstringsAsFactors = TRUEby default (and most users miss this subtlety). I say they are useful because model fitting packages like lme4 use factors and ordered factors to differentially fit models and determine the type of contrasts to use. And graphing packages also use them to group by.ggplotand most model fitting functions coerce character vectors to factors, so the result is the same. However, you end up with warnings in your code:One tricky thing is the whole
drop=TRUEbit. In vectors this works well to remove levels of factors that aren’t in the data. For example:However, with
data.frames, the behavior of[.data.frame()is different: see this email or?"[.data.frame". Usingdrop=TRUEondata.frames does not work as you’d imagine:Luckily you can drop factors easily with
droplevels()to drop unused factor levels for an individual factor or for every factor in adata.frame(since R 2.12):This is how to keep levels you’ve selected out from getting in
ggplotlegends.Internally,
factors are integers with an attribute level character vector (seeattributes(iris$Species)andclass(attributes(iris$Species)$levels)), which is clean. If you had to change a level name (and you were using character strings), this would be a much less efficient operation. And I change level names a lot, especially forggplotlegends. If you fake factors with character vectors, there’s the risk that you’ll change just one element, and accidentally create a separate new level.