Passing string variable to forcats::fct_reorder

笑着哭i 提交于 2019-12-20 06:12:28

问题


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?


回答1:


Ah solved

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


来源:https://stackoverflow.com/questions/54458018/passing-string-variable-to-forcatsfct-reorder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!