Use%>% to determine factor levels on the fly

I am trying to find a one-line parameter for assigning factor levels in the%>% command sequence.

My strategy for this was to run a sequence of functions on ., which gives ordered levels of factors that interest me. This results "Error: 'match' requires vector arguments"in an evaluation without use. gives 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 light on my mistake?

+4
source share
1 answer

How about this

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

All Articles