geotheory
geotheory

Reputation: 23690

Passing string variable to forcats::fct_reorder

Any idea how to pass a string sorting variable to fct_reorder?

require(dplyr)
require(forcats)
require(ggplot2)

order_var = 'displ'

mpg %>% mutate(manufacturer = fct_reorder(manufacturer, order_var))
#> Error in mutate_impl(.data, dots): Evaluation error: length(f) == length(.x) is not TRUE.

Tried with bang bang !!:

mpg %>% mutate(manufacturer = fct_reorder(manufacturer, !!order_var))
#> Error in mutate_impl(.data, dots): Evaluation error: length(f) == length(.x) is not TRUE.

Tried with eval:

as.name(eval(order_var))
#> displ

mpg %>% mutate(manufacturer = fct_reorder(manufacturer, as.name(eval(order_var))))
#> Error in mutate_impl(.data, dots): Evaluation error: length(f) == length(.x) is not TRUE.

Any suggestions?

Upvotes: 1

Views: 2150

Answers (1)

geotheory
geotheory

Reputation: 23690

Ah solved

mpg %>% mutate(manufacturer = fct_reorder(manufacturer, .[[order_var]]))

Upvotes: 2

Related Questions