编写一个tidyeval函数来重命名dplyr中的因子级别
我试图编写一个tidyeval函数,它接受一个数字列,用编写一个tidyeval函数来重命名dplyr中的因子级别,r,ggplot2,dplyr,tidyeval,R,Ggplot2,Dplyr,Tidyeval,我试图编写一个tidyeval函数,它接受一个数字列,用限制的值替换高于某个限制的值,将该列转换为一个因子,然后用一个名为“limit+”的级别替换等于限制的因子级别 例如,我试图用3替换sepal.width中高于3的任何值,然后将该因子级别重命名为3+ 作为一个例子,下面是我如何使用iris数据集。但是,fct_recode()函数没有正确重命名因子级别 plot_hist <- function(x, col, limit) { col_enq <- enquo(col)
限制
的值替换高于某个限制
的值,将该列转换为一个因子,然后用一个名为“limit+”的级别替换等于限制
的因子级别
例如,我试图用3替换sepal.width中高于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)
plot\u hist limit,limit,!!上校),,
var=fct_重新编码(var,赋值(粘贴(限制“+”,sep=”“),粘贴(限制)))
}
地块历史(虹膜,萼片宽度,3)
要修复最后一行,我们可以使用特殊符号:=
,因为我们需要在表达式的左侧设置值。对于RHS,我们需要强制为character,因为fct\u 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+
库(tidyverse)
绘图历史极限,极限!!上校),,
var=fct_重新编码(var,!!paste0(limit,“+”):=as.character(limit)))
}
地块历史(虹膜,萼片宽度,3)%>%
样本(10)
#>萼片。长萼片。宽花瓣。长花瓣。宽种变种
#>40 5.1 3.4 1.5 0.2 3+
#>98 6.2 2.9 4.3 1.3花色2.9
#>7.4.6 3.4 1.4 0.3第3段+
#>99 5.1 2.5 3.0 1.1 versicolor 2.5
#>76 6.6 3.0 4.4 1.4彩色3+
#>77 6.8 2.8 4.8 1.4花色2.8
#>85 5.4 3.0 4.5 1.5彩色3+
#>119 7.7 2.6 6.9 2.3弗吉尼亚州2.6
#>110 7.2 3.6 6.1 2.5弗吉尼亚州3+
#>103 7.1 3.0 5.9 2.1弗吉尼亚州3+
太棒了!非常感谢你!