reorder function within mutate

I'm trying this code:

crowdfund_tweets_clean %>%
  top_n(15) %>%
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(x = word, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
    labs(x = "Count",
         y = "Unique words",
         title = "Count of Unique Words found in Tweets")

And getting the following error:

Error: Problem with mutate() column word. i word = reorder(word, n). x arguments must have same length

What am I doing wrong?


You could use fct_reorder from forcats package: Here is an example:

library(forcats)
library(dplyr)
library(ggplot2)

mtcars %>%
  top_n(15) %>%
  mutate(gear = factor(gear)) %>% 
  add_count(gear) %>% 
  mutate(mpg = fct_reorder(gear, n)) %>%
  ggplot(aes(x = gear, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
  labs(x = "Count",
       y = "Unique words",
       title = "Count of Unique Words found in Tweets")

enter image description here