编写一个 tidyeval 函数来重命名 dplyr 中的因子水平

Write a tidyeval function to rename a factor level in a dplyr

我正在尝试编写一个带数字列的 tidyeval 函数,将高于某个 limit 的值替换为 limit 的值,将该列转换为一个因子,然后替换因子水平等于 limit,水平称为 "limit+"。

例如,我试图将 sepal.width 中任何高于 3 的值替换为 3,然后将该因子水平重命名为 3+

举个例子,下面是我试图让它与 iris 数据集一起工作的方法。但是,fct_recode() 函数没有正确重命名因子级别。

plot_hist <- function(x, col, limit) {
  col_enq <- enquo(col)
  x %>% 
    mutate(var = factor(ifelse(!!col_enq > limit, limit,!!col_enq)),
           var = fct_recode(var, assign(paste(limit,"+", sep = ""), paste(limit))))
}

plot_hist(iris, Sepal.Width, 3)

为了修复最后一行,我们可以使用特殊符号:=,因为我们需要设置表达式左侧的值。对于 RHS,我们需要强制转换为字符,因为 fct_recode 需要右侧的字符向量。

library(tidyverse)


plot_hist <- function(x, col, limit) {
  col_enq <- enquo(col)

  x %>% 
    mutate(var = factor(ifelse(!!col_enq > limit, limit, !!col_enq)),
           var = fct_recode(var, !!paste0(limit, "+") := as.character(limit)))
}

plot_hist(iris, Sepal.Width, 3) %>% 
  sample_n(10)
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species var
#> 40           5.1         3.4          1.5         0.2     setosa  3+
#> 98           6.2         2.9          4.3         1.3 versicolor 2.9
#> 7            4.6         3.4          1.4         0.3     setosa  3+
#> 99           5.1         2.5          3.0         1.1 versicolor 2.5
#> 76           6.6         3.0          4.4         1.4 versicolor  3+
#> 77           6.8         2.8          4.8         1.4 versicolor 2.8
#> 85           5.4         3.0          4.5         1.5 versicolor  3+
#> 119          7.7         2.6          6.9         2.3  virginica 2.6
#> 110          7.2         3.6          6.1         2.5  virginica  3+
#> 103          7.1         3.0          5.9         2.1  virginica  3+