4

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?

mtoto
  • 23,919
  • 4
  • 58
  • 71
shackett
  • 323
  • 2
  • 5

1 Answers1

2

How about this

data %>% 
  mutate(variable = factor(variable,
                           levels = variable %>% 
                             table() %>% 
                             data.frame() %>% 
                             arrange(-Freq) %>% 
                             select(1) %>% unlist()))
mtoto
  • 23,919
  • 4
  • 58
  • 71
  • I think your answer should cleanly handle 99% of cases. For the other 1% (when arranging by multiple variables), I was hoping to include _data_ as the first argument for factor levels – shackett Mar 11 '16 at 16:13