Trouble with fct_relevel()

I am trying to re-order the way my factor variables are listed and it is not working. The variable DMU has 20 levels that are the numbers 1-19 and Unknown. I created a tibble that counts how many times each unique factor occurs with the code

DMU_2020_Count <- data %>% group_by(DMU) %>% summarize(count=n())

However I would like the DMUs to be listed in numerical order (with unknown last) for presentation purposes. I've tried the code below but it doesn't give the desired product. It does not give an error message - just the following warning: Warning message:
Outer names are only allowed for unnamed scalar atomic inputs

DMU_2020_Count$DMU<-fct_relevel(DMU,levels=c('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','Unknown'))

I am fairly new to R and I really appreciate any help. Thanks!

Try arranging by that column after the fct_revel.

Can you elaborate?

Just use the arrange() with those specified levels?

I haven't got your data (provide a reproducible example next time), but like this:

library(tidyverse)
first_col_vals <-  c('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','Unknown')

# random order
df <- tibble(DMU = sample(first_col_vals),
             num = sample(1:20, 20, replace = TRUE)) 

# arranged by factor order
df %>% 
  mutate(DMU = factor(DMU, levels = first_col_vals)) %>% 
  arrange(DMU)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.