【问题标题】:Ordering bar chart in function using NSE?使用 NSE 在函数中排序条形图?
【发布时间】:2021-02-28 10:46:20
【问题描述】:

我目前正在尝试在 R 中订购条形图。该图是在函数中创建的,该函数使用传递的变量来选择列。这是基本功能:

plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, ))+
    aes_string(y = column_to_use)+
    geom_col()
}

plotting("Species")

这会产生正确的情节,但我仍然必须订购它。我已经尝试过 base-R reorder 和 forcats fct_reorder()。代码差异以粗体显示。


# reorder
plotting <- function(column_to_use) {
  ggplot(iris, aes(x = Sepal.Length, ))+
    aes_string(y = reorder(iris[column_to_use],Sepal.Width))+
    geom_col()
}

plotting("Species")

 > Error in tapply(X = X, INDEX = x, FUN = FUN, ...) : 
 object 'Sepal.Width' not found 

我正在使用 aes_string 使用非标准评估和图形转换变量列名,这在重新排序时不起作用。遗憾的是,没有可用的 reorder_ 对应物。


# fct_reorder
plotting <- function(column_to_use) {
  iris %>%
    fct_reorder(iris[column_to_use],Sepal.Width) %>%
    ggplot( aes(x = Sepal.Length))+
    aes_string(y = column_to_use)+
    geom_col()
}

plotting("Species")
> Error: `f` must be a factor (or character vector).

按 Sepal.Width 排序的条形图有哪些更好的选择?

【问题讨论】:

    标签: r function dplyr factors nse


    【解决方案1】:

    aes_string 已被软性弃用。尝试使用.data

    library(ggplot2)
    
    plotting <- function(column_to_use) {
      ggplot(iris, aes(x = Sepal.Length, 
                       y = reorder(.data[[column_to_use]], Sepal.Width)))+
        geom_col()
    }
    
    plotting("Species")
    

    【讨论】:

      【解决方案2】:

      我们可以转换为symbol 并使用!! 进行评估。它可以采用带引号和不带引号的输入

      library(ggplot2)
      plotting <- function(column_to_use) {
        ggplot(iris, aes(x = Sepal.Length, 
                     y = reorder(!! ensym(column_to_use), Sepal.Width)))+
         geom_col()
      }
      
      plotting("Species")
      plotting(Species)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        • 1970-01-01
        • 2017-03-02
        • 2021-04-22
        相关资源
        最近更新 更多