问题描述
我使用函数 step_num2factor()
创建的 last 类别正确创建了所有级别,但最后一个级别。在那里它填充了一个 NA。
MWE
test <- tibble(pred = c(0,1,2,3,4,5,8),target = c(0,0))
打印时看起来像这样:
# A tibble: 7 x 2
pred target
<dbl> <dbl>
1 0 0
2 1 1
3 2 0
4 3 1
5 4 1
6 5 1
7 8 0
执行配方步骤并比较结果
test <- tibble(pred = c(0,0))
my_levels <- c("zero","one","two","three","four","five","eight")
recipe(target ~ pred,data = test) %>%
step_num2factor(pred,levels = my_levels,transform = function(x) x + 1) %>%
prep(training = test) %>%
bake(new_data = test)
准备和烘焙后转换后的数据集
# A tibble: 7 x 2
pred target
<fct> <dbl>
1 zero 0
2 one 1
3 two 0
4 three 1
5 four 1
6 five 1
7 NA 0
NA 不应该在那里。它应该是“八”类。我做错了什么?
备注:我也用“六”试过了,因为我认为该函数可能只接受单词中的值,而不是完全随机命名的级别,但也不是那样。
解决方法
您需要确保您的输入、级别和 transform
完美匹配。
您使用 transform = function(x) x + 1
是正确的,因为您正在尝试捕获 0
。因此,当您的输入为 n
时,则选择 n+1
的 levels
th 值。
当您的输入为 8
时,step_num2factor()
返回 8+1=9
的 levels
th 值,该值不存在,因为它的长度仅为 7
,导致您看到的 NA
。下面的代码应该说明问题
library(recipes)
my_levels <- c("zero","one","two","three","four","five","eight")
test <- tibble(pred = c(0,1,2,3,4,5,6),target = c(0,0))
recipe(target ~ pred,data = test) %>%
step_num2factor(pred,levels = my_levels,transform = function(x) x + 1) %>%
prep() %>%
bake(new_data = NULL)
#> # A tibble: 7 x 2
#> pred target
#> <fct> <dbl>
#> 1 zero 0
#> 2 one 1
#> 3 two 0
#> 4 three 1
#> 5 four 1
#> 6 five 1
#> 7 eight 0
要解决您的问题,您需要确保 my_levels
test <- tibble(pred = c(0,8),0))
my_levels <- c("zero","six","seven","eight","nine","ten")
recipe(target ~ pred,transform = function(x) x + 1) %>%
prep() %>%
bake(new_data = NULL)
#> # A tibble: 7 x 2
#> pred target
#> <fct> <dbl>
#> 1 zero 0
#> 2 one 1
#> 3 two 0
#> 4 three 1
#> 5 four 1
#> 6 five 1
#> 7 eight 0
由 reprex package (v0.3.0) 于 2021 年 3 月 27 日创建