Drop unused factor levels
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
When creating a subset of a dataframe, I often exclude rows based on the level of a factor. However, the “levels” of the factor remain intact. This is the intended behavior of R, but it can cause problems in some cases. I finally discovered how to clean up levels in this post to R-Help. Here is an example:
> a <- factor(letters) > a [1] a b c d e f g h i j k l m n o p q r s t u v w x y z Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z ## Now, even though b only includes five letters, ## all 26 are listed in the levels > b <- a[1:5] > b [1] a b c d e Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z ## This behavior can be changed using the following syntax: > b <- a[1:5,drop = TRUE] > b [1] a b c d e Levels: a b c d e
Another way to deal with this is to use the dropUnusedLevels() command in the Hmisc library. The only issue here is that behavior is changed globally which may have undesired consequences (see the post listed above).
****UPDATE****
As Jeff Hollister mentions in the comments, there is another way to do this:
a
var vglnk = {key: '949efb41171ac6ec1bf7f206d57e90b8'};
(function(d, t) {
var s = d.createElement(t);
s.type = 'text/javascript';
s.async = true;
// s.defer = true;
// s.src = '//cdn.viglink.com/api/vglnk.js';
s.src = 'https://www.r-bloggers.com/wp-content/uploads/2020/08/vglnk.js';
var r = d.getElementsByTagName(t)[0];
r.parentNode.insertBefore(s, r);
}(document, 'script'));
options(stringsAsFactors = FALSE)
a
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.