Error in `fct_reorder()`: ! `.f` must be a factor or character vector, not a data frame - trying to reorder a bar plot

1.2k Views Asked by At

I have a summary table with means for 4 variables from a dataset with 940 rows:

activity_means <- activity_daily_clean %>%
  summarize(sedentary = mean(sedentary_minutes),
            lightly_active = mean(lightly_active_minutes),
            fairly_active = mean(fairly_active_minutes),
            very_active = mean(very_active_minutes))

I want to plot them into a simple bar plot, but the levels of activity intensity (sedentary - lightly active - fairly active - very active) appear disorganized:

act_means_df <- data.frame(
  activity_intensity=c("sedentary", "lightly active", "fairly active", "very active"),
  intens_means=c(991.2106, 192.8128, 13.56489, 21.16489)
)

ggplot(act_means_df)+
  geom_col(aes(x=activity_intensity, y=intens_means))

disorganized bar plot

I tried following the guide in the R Graph Gallery to reorder a bar plot following the values from the second variable:

act_means_df <- data.frame(
  activity_intensity=c("sedentary", "lightly active", "fairly active", "very active"),
  intens_means=c(991.2106, 192.8128, 13.56489, 21.16489)
) %>%
  mutate(f_act_int = factor(activity_intensity))

act_means_df %>%
  fct_reorder(f_act_int, intens_means) %>%
  ggplot(aes(x=f_act_int, y=intens_means))+
  geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
  coord_flip() +
  xlab("") +
  theme_bw()

But the following error appears when I run the last chunk: Error in fct_reorder(): ! .f must be a factor or character vector, not a data frame

I confirmed whether f_act_int is a factor with: str(act_means_df): 'data.frame': 4 obs. of 3 variables: $ activity_intensity: chr "sedentary" "lightly active" "fairly active" "very active" $ intens_means : num 991.2 192.8 13.6 21.2 $ f_act_int : Factor w/ 4 levels "fairly active",..: 3 2 1 4

But when I try to inspect the object by itself with class(f_act_int), the error message says "object 'f_act_int' not found".

Does anybody know what I am missing?

1

There are 1 best solutions below

2
Captain Hat On

You need to use fct_reorder within dplyr::mutate().

This isn't the only way to solve this issue, but the gist of your error is that you're passing your whole data frame, when it expects a factor or character vector. Instead, try this:

act_means_df %>%
  mutate(fa_act_in = fct_reorder(f_act_int, intens_means)) %>%
  ggplot(aes(x=f_act_int, y=intens_means))+
  geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
  coord_flip() +
  xlab("") +
  theme_bw()

There is no object in your global environment called f_act_in; When you call fct_reorder() within mutate(), R looks inside your data frame for a column with that name, upon which performs the operation in order to return an updated data frame. This updated data frame is then passed to ggplot().