Search code examples
rdplyrmagrittr

Using %>% to specify factor levels on the fly


I am trying to find a one-line option to assign factor levels within a sequence of %>% commands.

My strategy for doing this was to run a sequence of functions on . that yields the ordered factor levels I am interested in. This results in "Error: 'match' requires vector arguments", while evaluating without using . yields the appropriate levels.

library(dplyr)
library(magrittr)

data = data.frame(variable = LETTERS[c(1:4,2:4,3:4)])

data %>% count(variable) %>% arrange(desc(n)) %$% variable

# returns C D B A

data %>% mutate(variable = factor(variable, levels = . %>% count(variable) %>% arrange(desc(n)) %$% variable))

# Error: 'match' requires vector arguments

Can anyone think of a better way to do this, or shed some light on my error?


Solution

  • How about this

    data %>% 
      mutate(variable = factor(variable,
                               levels = variable %>% 
                                 table() %>% 
                                 data.frame() %>% 
                                 arrange(-Freq) %>% 
                                 select(1) %>% unlist()))