写一个tidyeval函数来重命名dplyr中的因子级别

Har*_*y M 2 r ggplot2 dplyr tidyeval

我正在尝试编写一个tidyeval函数,该函数接受一个数字列,用值替换某个值以上limit的值limit,将该列转换为一个因子,然后将因子级别替换为limit一个名为"limit +"的级别.

例如,我试图用sepal.width替换3以上的任何值,然后将该因子级别重命名为3+.

作为一个例子,这是我试图使它与虹膜数据集一起工作的方式.但是,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)
Run Code Online (Sandbox Code Playgroud)

Tho*_*s K 5

要修复最后一行,我们可以使用特殊符号:=,因为我们需要在表达式的左侧设置值.对于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+
Run Code Online (Sandbox Code Playgroud)